clang  17.0.0git
SemaExpr.cpp
Go to the documentation of this file.
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Designator.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/ExprOpenMP.h"
31 #include "clang/AST/Type.h"
32 #include "clang/AST/TypeLoc.h"
33 #include "clang/Basic/Builtins.h"
37 #include "clang/Basic/Specifiers.h"
38 #include "clang/Basic/TargetInfo.h"
40 #include "clang/Lex/Preprocessor.h"
42 #include "clang/Sema/DeclSpec.h"
45 #include "clang/Sema/Lookup.h"
46 #include "clang/Sema/Overload.h"
48 #include "clang/Sema/Scope.h"
49 #include "clang/Sema/ScopeInfo.h"
52 #include "clang/Sema/Template.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include "llvm/Support/TypeSize.h"
59 #include <optional>
60 
61 using namespace clang;
62 using namespace sema;
63 
64 /// Determine whether the use of this declaration is valid, without
65 /// emitting diagnostics.
66 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
67  // See if this is an auto-typed variable whose initializer we are parsing.
68  if (ParsingInitForAutoVars.count(D))
69  return false;
70 
71  // See if this is a deleted function.
72  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73  if (FD->isDeleted())
74  return false;
75 
76  // If the function has a deduced return type, and we can't deduce it,
77  // then we can't use it either.
78  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
79  DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
80  return false;
81 
82  // See if this is an aligned allocation/deallocation function that is
83  // unavailable.
84  if (TreatUnavailableAsInvalid &&
85  isUnavailableAlignedAllocationFunction(*FD))
86  return false;
87  }
88 
89  // See if this function is unavailable.
90  if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
91  cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
92  return false;
93 
94  if (isa<UnresolvedUsingIfExistsDecl>(D))
95  return false;
96 
97  return true;
98 }
99 
101  // Warn if this is used but marked unused.
102  if (const auto *A = D->getAttr<UnusedAttr>()) {
103  // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
104  // should diagnose them.
105  if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
106  A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
107  const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
108  if (DC && !DC->hasAttr<UnusedAttr>())
109  S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
110  }
111  }
112 }
113 
114 /// Emit a note explaining that this function is deleted.
116  assert(Decl && Decl->isDeleted());
117 
118  if (Decl->isDefaulted()) {
119  // If the method was explicitly defaulted, point at that declaration.
120  if (!Decl->isImplicit())
121  Diag(Decl->getLocation(), diag::note_implicitly_deleted);
122 
123  // Try to diagnose why this special member function was implicitly
124  // deleted. This might fail, if that reason no longer applies.
125  DiagnoseDeletedDefaultedFunction(Decl);
126  return;
127  }
128 
129  auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
130  if (Ctor && Ctor->isInheritingConstructor())
131  return NoteDeletedInheritingConstructor(Ctor);
132 
133  Diag(Decl->getLocation(), diag::note_availability_specified_here)
134  << Decl << 1;
135 }
136 
137 /// Determine whether a FunctionDecl was ever declared with an
138 /// explicit storage class.
140  for (auto *I : D->redecls()) {
141  if (I->getStorageClass() != SC_None)
142  return true;
143  }
144  return false;
145 }
146 
147 /// Check whether we're in an extern inline function and referring to a
148 /// variable or function with internal linkage (C11 6.7.4p3).
149 ///
150 /// This is only a warning because we used to silently accept this code, but
151 /// in many cases it will not behave correctly. This is not enabled in C++ mode
152 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
153 /// and so while there may still be user mistakes, most of the time we can't
154 /// prove that there are errors.
156  const NamedDecl *D,
157  SourceLocation Loc) {
158  // This is disabled under C++; there are too many ways for this to fire in
159  // contexts where the warning is a false positive, or where it is technically
160  // correct but benign.
161  if (S.getLangOpts().CPlusPlus)
162  return;
163 
164  // Check if this is an inlined function or method.
165  FunctionDecl *Current = S.getCurFunctionDecl();
166  if (!Current)
167  return;
168  if (!Current->isInlined())
169  return;
170  if (!Current->isExternallyVisible())
171  return;
172 
173  // Check if the decl has internal linkage.
174  if (D->getFormalLinkage() != InternalLinkage)
175  return;
176 
177  // Downgrade from ExtWarn to Extension if
178  // (1) the supposedly external inline function is in the main file,
179  // and probably won't be included anywhere else.
180  // (2) the thing we're referencing is a pure function.
181  // (3) the thing we're referencing is another inline function.
182  // This last can give us false negatives, but it's better than warning on
183  // wrappers for simple C library functions.
184  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
185  bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
186  if (!DowngradeWarning && UsedFn)
187  DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
188 
189  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
190  : diag::ext_internal_in_extern_inline)
191  << /*IsVar=*/!UsedFn << D;
192 
194 
195  S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
196  << D;
197 }
198 
200  const FunctionDecl *First = Cur->getFirstDecl();
201 
202  // Suggest "static" on the function, if possible.
204  SourceLocation DeclBegin = First->getSourceRange().getBegin();
205  Diag(DeclBegin, diag::note_convert_inline_to_static)
206  << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
207  }
208 }
209 
210 /// Determine whether the use of this declaration is valid, and
211 /// emit any corresponding diagnostics.
212 ///
213 /// This routine diagnoses various problems with referencing
214 /// declarations that can occur when using a declaration. For example,
215 /// it might warn if a deprecated or unavailable declaration is being
216 /// used, or produce an error (and return true) if a C++0x deleted
217 /// function is being used.
218 ///
219 /// \returns true if there was an error (this declaration cannot be
220 /// referenced), false otherwise.
221 ///
223  const ObjCInterfaceDecl *UnknownObjCClass,
224  bool ObjCPropertyAccess,
225  bool AvoidPartialAvailabilityChecks,
226  ObjCInterfaceDecl *ClassReceiver,
227  bool SkipTrailingRequiresClause) {
228  SourceLocation Loc = Locs.front();
229  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
230  // If there were any diagnostics suppressed by template argument deduction,
231  // emit them now.
232  auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
233  if (Pos != SuppressedDiagnostics.end()) {
234  for (const PartialDiagnosticAt &Suppressed : Pos->second)
235  Diag(Suppressed.first, Suppressed.second);
236 
237  // Clear out the list of suppressed diagnostics, so that we don't emit
238  // them again for this specialization. However, we don't obsolete this
239  // entry from the table, because we want to avoid ever emitting these
240  // diagnostics again.
241  Pos->second.clear();
242  }
243 
244  // C++ [basic.start.main]p3:
245  // The function 'main' shall not be used within a program.
246  if (cast<FunctionDecl>(D)->isMain())
247  Diag(Loc, diag::ext_main_used);
248 
249  diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
250  }
251 
252  // See if this is an auto-typed variable whose initializer we are parsing.
253  if (ParsingInitForAutoVars.count(D)) {
254  if (isa<BindingDecl>(D)) {
255  Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
256  << D->getDeclName();
257  } else {
258  Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
259  << D->getDeclName() << cast<VarDecl>(D)->getType();
260  }
261  return true;
262  }
263 
264  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
265  // See if this is a deleted function.
266  if (FD->isDeleted()) {
267  auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
268  if (Ctor && Ctor->isInheritingConstructor())
269  Diag(Loc, diag::err_deleted_inherited_ctor_use)
270  << Ctor->getParent()
271  << Ctor->getInheritedConstructor().getConstructor()->getParent();
272  else
273  Diag(Loc, diag::err_deleted_function_use);
274  NoteDeletedFunction(FD);
275  return true;
276  }
277 
278  // [expr.prim.id]p4
279  // A program that refers explicitly or implicitly to a function with a
280  // trailing requires-clause whose constraint-expression is not satisfied,
281  // other than to declare it, is ill-formed. [...]
282  //
283  // See if this is a function with constraints that need to be satisfied.
284  // Check this before deducing the return type, as it might instantiate the
285  // definition.
286  if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
287  ConstraintSatisfaction Satisfaction;
288  if (CheckFunctionConstraints(FD, Satisfaction, Loc,
289  /*ForOverloadResolution*/ true))
290  // A diagnostic will have already been generated (non-constant
291  // constraint expression, for example)
292  return true;
293  if (!Satisfaction.IsSatisfied) {
294  Diag(Loc,
295  diag::err_reference_to_function_with_unsatisfied_constraints)
296  << D;
297  DiagnoseUnsatisfiedConstraint(Satisfaction);
298  return true;
299  }
300  }
301 
302  // If the function has a deduced return type, and we can't deduce it,
303  // then we can't use it either.
304  if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
305  DeduceReturnType(FD, Loc))
306  return true;
307 
308  if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
309  return true;
310 
311  if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
312  return true;
313  }
314 
315  if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
316  // Lambdas are only default-constructible or assignable in C++2a onwards.
317  if (MD->getParent()->isLambda() &&
318  ((isa<CXXConstructorDecl>(MD) &&
319  cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
320  MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
321  Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
322  << !isa<CXXConstructorDecl>(MD);
323  }
324  }
325 
326  auto getReferencedObjCProp = [](const NamedDecl *D) ->
327  const ObjCPropertyDecl * {
328  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
329  return MD->findPropertyDecl();
330  return nullptr;
331  };
332  if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
333  if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
334  return true;
335  } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
336  return true;
337  }
338 
339  // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
340  // Only the variables omp_in and omp_out are allowed in the combiner.
341  // Only the variables omp_priv and omp_orig are allowed in the
342  // initializer-clause.
343  auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
344  if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
345  isa<VarDecl>(D)) {
346  Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
347  << getCurFunction()->HasOMPDeclareReductionCombiner;
348  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
349  return true;
350  }
351 
352  // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
353  // List-items in map clauses on this construct may only refer to the declared
354  // variable var and entities that could be referenced by a procedure defined
355  // at the same location.
356  // [OpenMP 5.2] Also allow iterator declared variables.
357  if (LangOpts.OpenMP && isa<VarDecl>(D) &&
358  !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
359  Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
360  << getOpenMPDeclareMapperVarName();
361  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
362  return true;
363  }
364 
365  if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
366  Diag(Loc, diag::err_use_of_empty_using_if_exists);
367  Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
368  return true;
369  }
370 
371  DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
372  AvoidPartialAvailabilityChecks, ClassReceiver);
373 
374  DiagnoseUnusedOfDecl(*this, D, Loc);
375 
377 
378  if (auto *VD = dyn_cast<ValueDecl>(D))
379  checkTypeSupport(VD->getType(), Loc, VD);
380 
381  if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
382  if (!Context.getTargetInfo().isTLSSupported())
383  if (const auto *VD = dyn_cast<VarDecl>(D))
384  if (VD->getTLSKind() != VarDecl::TLS_None)
385  targetDiag(*Locs.begin(), diag::err_thread_unsupported);
386  }
387 
388  if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
389  !isUnevaluatedContext()) {
390  // C++ [expr.prim.req.nested] p3
391  // A local parameter shall only appear as an unevaluated operand
392  // (Clause 8) within the constraint-expression.
393  Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
394  << D;
395  Diag(D->getLocation(), diag::note_entity_declared_at) << D;
396  return true;
397  }
398 
399  return false;
400 }
401 
402 /// DiagnoseSentinelCalls - This routine checks whether a call or
403 /// message-send is to a declaration with the sentinel attribute, and
404 /// if so, it checks that the requirements of the sentinel are
405 /// satisfied.
407  ArrayRef<Expr *> Args) {
408  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
409  if (!attr)
410  return;
411 
412  // The number of formal parameters of the declaration.
413  unsigned numFormalParams;
414 
415  // The kind of declaration. This is also an index into a %select in
416  // the diagnostic.
417  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
418 
419  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
420  numFormalParams = MD->param_size();
421  calleeType = CT_Method;
422  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
423  numFormalParams = FD->param_size();
424  calleeType = CT_Function;
425  } else if (isa<VarDecl>(D)) {
426  QualType type = cast<ValueDecl>(D)->getType();
427  const FunctionType *fn = nullptr;
428  if (const PointerType *ptr = type->getAs<PointerType>()) {
429  fn = ptr->getPointeeType()->getAs<FunctionType>();
430  if (!fn) return;
431  calleeType = CT_Function;
432  } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
433  fn = ptr->getPointeeType()->castAs<FunctionType>();
434  calleeType = CT_Block;
435  } else {
436  return;
437  }
438 
439  if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
440  numFormalParams = proto->getNumParams();
441  } else {
442  numFormalParams = 0;
443  }
444  } else {
445  return;
446  }
447 
448  // "nullPos" is the number of formal parameters at the end which
449  // effectively count as part of the variadic arguments. This is
450  // useful if you would prefer to not have *any* formal parameters,
451  // but the language forces you to have at least one.
452  unsigned nullPos = attr->getNullPos();
453  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
454  numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
455 
456  // The number of arguments which should follow the sentinel.
457  unsigned numArgsAfterSentinel = attr->getSentinel();
458 
459  // If there aren't enough arguments for all the formal parameters,
460  // the sentinel, and the args after the sentinel, complain.
461  if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
462  Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
463  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
464  return;
465  }
466 
467  // Otherwise, find the sentinel expression.
468  Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
469  if (!sentinelExpr) return;
470  if (sentinelExpr->isValueDependent()) return;
471  if (Context.isSentinelNullExpr(sentinelExpr)) return;
472 
473  // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
474  // or 'NULL' if those are actually defined in the context. Only use
475  // 'nil' for ObjC methods, where it's much more likely that the
476  // variadic arguments form a list of object pointers.
477  SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
478  std::string NullValue;
479  if (calleeType == CT_Method && PP.isMacroDefined("nil"))
480  NullValue = "nil";
481  else if (getLangOpts().CPlusPlus11)
482  NullValue = "nullptr";
483  else if (PP.isMacroDefined("NULL"))
484  NullValue = "NULL";
485  else
486  NullValue = "(void*) 0";
487 
488  if (MissingNilLoc.isInvalid())
489  Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
490  else
491  Diag(MissingNilLoc, diag::warn_missing_sentinel)
492  << int(calleeType)
493  << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
494  Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
495 }
496 
498  return E ? E->getSourceRange() : SourceRange();
499 }
500 
501 //===----------------------------------------------------------------------===//
502 // Standard Promotions and Conversions
503 //===----------------------------------------------------------------------===//
504 
505 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
507  // Handle any placeholder expressions which made it here.
508  if (E->hasPlaceholderType()) {
509  ExprResult result = CheckPlaceholderExpr(E);
510  if (result.isInvalid()) return ExprError();
511  E = result.get();
512  }
513 
514  QualType Ty = E->getType();
515  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
516 
517  if (Ty->isFunctionType()) {
518  if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
519  if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
520  if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
521  return ExprError();
522 
523  E = ImpCastExprToType(E, Context.getPointerType(Ty),
524  CK_FunctionToPointerDecay).get();
525  } else if (Ty->isArrayType()) {
526  // In C90 mode, arrays only promote to pointers if the array expression is
527  // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
528  // type 'array of type' is converted to an expression that has type 'pointer
529  // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
530  // that has type 'array of type' ...". The relevant change is "an lvalue"
531  // (C90) to "an expression" (C99).
532  //
533  // C++ 4.2p1:
534  // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
535  // T" can be converted to an rvalue of type "pointer to T".
536  //
537  if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
538  ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
539  CK_ArrayToPointerDecay);
540  if (Res.isInvalid())
541  return ExprError();
542  E = Res.get();
543  }
544  }
545  return E;
546 }
547 
549  // Check to see if we are dereferencing a null pointer. If so,
550  // and if not volatile-qualified, this is undefined behavior that the
551  // optimizer will delete, so warn about it. People sometimes try to use this
552  // to get a deterministic trap and are surprised by clang's behavior. This
553  // only handles the pattern "*null", which is a very syntactic check.
554  const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
555  if (UO && UO->getOpcode() == UO_Deref &&
556  UO->getSubExpr()->getType()->isPointerType()) {
557  const LangAS AS =
558  UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
559  if ((!isTargetAddressSpace(AS) ||
560  (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
561  UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
563  !UO->getType().isVolatileQualified()) {
564  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
565  S.PDiag(diag::warn_indirection_through_null)
566  << UO->getSubExpr()->getSourceRange());
567  S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
568  S.PDiag(diag::note_indirection_through_null));
569  }
570  }
571 }
572 
573 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
574  SourceLocation AssignLoc,
575  const Expr* RHS) {
576  const ObjCIvarDecl *IV = OIRE->getDecl();
577  if (!IV)
578  return;
579 
580  DeclarationName MemberName = IV->getDeclName();
581  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
582  if (!Member || !Member->isStr("isa"))
583  return;
584 
585  const Expr *Base = OIRE->getBase();
586  QualType BaseType = Base->getType();
587  if (OIRE->isArrow())
588  BaseType = BaseType->getPointeeType();
589  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
590  if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
591  ObjCInterfaceDecl *ClassDeclared = nullptr;
592  ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
593  if (!ClassDeclared->getSuperClass()
594  && (*ClassDeclared->ivar_begin()) == IV) {
595  if (RHS) {
596  NamedDecl *ObjectSetClass =
598  &S.Context.Idents.get("object_setClass"),
600  if (ObjectSetClass) {
601  SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
602  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
604  "object_setClass(")
606  SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
607  << FixItHint::CreateInsertion(RHSLocEnd, ")");
608  }
609  else
610  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
611  } else {
612  NamedDecl *ObjectGetClass =
614  &S.Context.Idents.get("object_getClass"),
616  if (ObjectGetClass)
617  S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
619  "object_getClass(")
621  SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
622  else
623  S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
624  }
625  S.Diag(IV->getLocation(), diag::note_ivar_decl);
626  }
627  }
628 }
629 
631  // Handle any placeholder expressions which made it here.
632  if (E->hasPlaceholderType()) {
633  ExprResult result = CheckPlaceholderExpr(E);
634  if (result.isInvalid()) return ExprError();
635  E = result.get();
636  }
637 
638  // C++ [conv.lval]p1:
639  // A glvalue of a non-function, non-array type T can be
640  // converted to a prvalue.
641  if (!E->isGLValue()) return E;
642 
643  QualType T = E->getType();
644  assert(!T.isNull() && "r-value conversion on typeless expression?");
645 
646  // lvalue-to-rvalue conversion cannot be applied to function or array types.
647  if (T->isFunctionType() || T->isArrayType())
648  return E;
649 
650  // We don't want to throw lvalue-to-rvalue casts on top of
651  // expressions of certain types in C++.
652  if (getLangOpts().CPlusPlus &&
653  (E->getType() == Context.OverloadTy ||
654  T->isDependentType() ||
655  T->isRecordType()))
656  return E;
657 
658  // The C standard is actually really unclear on this point, and
659  // DR106 tells us what the result should be but not why. It's
660  // generally best to say that void types just doesn't undergo
661  // lvalue-to-rvalue at all. Note that expressions of unqualified
662  // 'void' type are never l-values, but qualified void can be.
663  if (T->isVoidType())
664  return E;
665 
666  // OpenCL usually rejects direct accesses to values of 'half' type.
667  if (getLangOpts().OpenCL &&
668  !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
669  T->isHalfType()) {
670  Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
671  << 0 << T;
672  return ExprError();
673  }
674 
676  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
677  NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
678  &Context.Idents.get("object_getClass"),
679  SourceLocation(), LookupOrdinaryName);
680  if (ObjectGetClass)
681  Diag(E->getExprLoc(), diag::warn_objc_isa_use)
682  << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
684  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
685  else
686  Diag(E->getExprLoc(), diag::warn_objc_isa_use);
687  }
688  else if (const ObjCIvarRefExpr *OIRE =
689  dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
690  DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
691 
692  // C++ [conv.lval]p1:
693  // [...] If T is a non-class type, the type of the prvalue is the
694  // cv-unqualified version of T. Otherwise, the type of the
695  // rvalue is T.
696  //
697  // C99 6.3.2.1p2:
698  // If the lvalue has qualified type, the value has the unqualified
699  // version of the type of the lvalue; otherwise, the value has the
700  // type of the lvalue.
701  if (T.hasQualifiers())
702  T = T.getUnqualifiedType();
703 
704  // Under the MS ABI, lock down the inheritance model now.
705  if (T->isMemberPointerType() &&
706  Context.getTargetInfo().getCXXABI().isMicrosoft())
707  (void)isCompleteType(E->getExprLoc(), T);
708 
709  ExprResult Res = CheckLValueToRValueConversionOperand(E);
710  if (Res.isInvalid())
711  return Res;
712  E = Res.get();
713 
714  // Loading a __weak object implicitly retains the value, so we need a cleanup to
715  // balance that.
717  Cleanup.setExprNeedsCleanups(true);
718 
720  Cleanup.setExprNeedsCleanups(true);
721 
722  // C++ [conv.lval]p3:
723  // If T is cv std::nullptr_t, the result is a null pointer constant.
724  CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
725  Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
726  CurFPFeatureOverrides());
727 
728  // C11 6.3.2.1p2:
729  // ... if the lvalue has atomic type, the value has the non-atomic version
730  // of the type of the lvalue ...
731  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
732  T = Atomic->getValueType().getUnqualifiedType();
733  Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
734  nullptr, VK_PRValue, FPOptionsOverride());
735  }
736 
737  return Res;
738 }
739 
741  ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
742  if (Res.isInvalid())
743  return ExprError();
744  Res = DefaultLvalueConversion(Res.get());
745  if (Res.isInvalid())
746  return ExprError();
747  return Res;
748 }
749 
750 /// CallExprUnaryConversions - a special case of an unary conversion
751 /// performed on a function designator of a call expression.
753  QualType Ty = E->getType();
754  ExprResult Res = E;
755  // Only do implicit cast for a function type, but not for a pointer
756  // to function type.
757  if (Ty->isFunctionType()) {
758  Res = ImpCastExprToType(E, Context.getPointerType(Ty),
759  CK_FunctionToPointerDecay);
760  if (Res.isInvalid())
761  return ExprError();
762  }
763  Res = DefaultLvalueConversion(Res.get());
764  if (Res.isInvalid())
765  return ExprError();
766  return Res.get();
767 }
768 
769 /// UsualUnaryConversions - Performs various conversions that are common to most
770 /// operators (C99 6.3). The conversions of array and function types are
771 /// sometimes suppressed. For example, the array->pointer conversion doesn't
772 /// apply if the array is an argument to the sizeof or address (&) operators.
773 /// In these instances, this routine should *not* be called.
775  // First, convert to an r-value.
776  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
777  if (Res.isInvalid())
778  return ExprError();
779  E = Res.get();
780 
781  QualType Ty = E->getType();
782  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
783 
784  LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
785  if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
786  (getLangOpts().getFPEvalMethod() !=
787  LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
788  PP.getLastFPEvalPragmaLocation().isValid())) {
789  switch (EvalMethod) {
790  default:
791  llvm_unreachable("Unrecognized float evaluation method");
792  break;
794  llvm_unreachable("Float evaluation method should be set by now");
795  break;
797  if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
798  // Widen the expression to double.
799  return Ty->isComplexType()
800  ? ImpCastExprToType(E,
801  Context.getComplexType(Context.DoubleTy),
802  CK_FloatingComplexCast)
803  : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
804  break;
806  if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
807  // Widen the expression to long double.
808  return Ty->isComplexType()
809  ? ImpCastExprToType(
810  E, Context.getComplexType(Context.LongDoubleTy),
811  CK_FloatingComplexCast)
812  : ImpCastExprToType(E, Context.LongDoubleTy,
813  CK_FloatingCast);
814  break;
815  }
816  }
817 
818  // Half FP have to be promoted to float unless it is natively supported
819  if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
820  return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
821 
822  // Try to perform integral promotions if the object has a theoretically
823  // promotable type.
825  // C99 6.3.1.1p2:
826  //
827  // The following may be used in an expression wherever an int or
828  // unsigned int may be used:
829  // - an object or expression with an integer type whose integer
830  // conversion rank is less than or equal to the rank of int
831  // and unsigned int.
832  // - A bit-field of type _Bool, int, signed int, or unsigned int.
833  //
834  // If an int can represent all values of the original type, the
835  // value is converted to an int; otherwise, it is converted to an
836  // unsigned int. These are called the integer promotions. All
837  // other types are unchanged by the integer promotions.
838 
839  QualType PTy = Context.isPromotableBitField(E);
840  if (!PTy.isNull()) {
841  E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
842  return E;
843  }
844  if (Context.isPromotableIntegerType(Ty)) {
845  QualType PT = Context.getPromotedIntegerType(Ty);
846  E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
847  return E;
848  }
849  }
850  return E;
851 }
852 
853 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
854 /// do not have a prototype. Arguments that have type float or __fp16
855 /// are promoted to double. All other argument types are converted by
856 /// UsualUnaryConversions().
858  QualType Ty = E->getType();
859  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
860 
861  ExprResult Res = UsualUnaryConversions(E);
862  if (Res.isInvalid())
863  return ExprError();
864  E = Res.get();
865 
866  // If this is a 'float' or '__fp16' (CVR qualified or typedef)
867  // promote to double.
868  // Note that default argument promotion applies only to float (and
869  // half/fp16); it does not apply to _Float16.
870  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
871  if (BTy && (BTy->getKind() == BuiltinType::Half ||
872  BTy->getKind() == BuiltinType::Float)) {
873  if (getLangOpts().OpenCL &&
874  !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
875  if (BTy->getKind() == BuiltinType::Half) {
876  E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
877  }
878  } else {
879  E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
880  }
881  }
882  if (BTy &&
883  getLangOpts().getExtendIntArgs() ==
885  Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
886  Context.getTypeSizeInChars(BTy) <
887  Context.getTypeSizeInChars(Context.LongLongTy)) {
888  E = (Ty->isUnsignedIntegerType())
889  ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
890  .get()
891  : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
892  assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
893  "Unexpected typesize for LongLongTy");
894  }
895 
896  // C++ performs lvalue-to-rvalue conversion as a default argument
897  // promotion, even on class types, but note:
898  // C++11 [conv.lval]p2:
899  // When an lvalue-to-rvalue conversion occurs in an unevaluated
900  // operand or a subexpression thereof the value contained in the
901  // referenced object is not accessed. Otherwise, if the glvalue
902  // has a class type, the conversion copy-initializes a temporary
903  // of type T from the glvalue and the result of the conversion
904  // is a prvalue for the temporary.
905  // FIXME: add some way to gate this entire thing for correctness in
906  // potentially potentially evaluated contexts.
907  if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
908  ExprResult Temp = PerformCopyInitialization(
910  E->getExprLoc(), E);
911  if (Temp.isInvalid())
912  return ExprError();
913  E = Temp.get();
914  }
915 
916  return E;
917 }
918 
919 /// Determine the degree of POD-ness for an expression.
920 /// Incomplete types are considered POD, since this check can be performed
921 /// when we're in an unevaluated context.
923  if (Ty->isIncompleteType()) {
924  // C++11 [expr.call]p7:
925  // After these conversions, if the argument does not have arithmetic,
926  // enumeration, pointer, pointer to member, or class type, the program
927  // is ill-formed.
928  //
929  // Since we've already performed array-to-pointer and function-to-pointer
930  // decay, the only such type in C++ is cv void. This also handles
931  // initializer lists as variadic arguments.
932  if (Ty->isVoidType())
933  return VAK_Invalid;
934 
935  if (Ty->isObjCObjectType())
936  return VAK_Invalid;
937  return VAK_Valid;
938  }
939 
941  return VAK_Invalid;
942 
943  if (Ty.isCXX98PODType(Context))
944  return VAK_Valid;
945 
946  // C++11 [expr.call]p7:
947  // Passing a potentially-evaluated argument of class type (Clause 9)
948  // having a non-trivial copy constructor, a non-trivial move constructor,
949  // or a non-trivial destructor, with no corresponding parameter,
950  // is conditionally-supported with implementation-defined semantics.
951  if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
952  if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
953  if (!Record->hasNonTrivialCopyConstructor() &&
954  !Record->hasNonTrivialMoveConstructor() &&
955  !Record->hasNonTrivialDestructor())
956  return VAK_ValidInCXX11;
957 
958  if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
959  return VAK_Valid;
960 
961  if (Ty->isObjCObjectType())
962  return VAK_Invalid;
963 
964  if (getLangOpts().MSVCCompat)
965  return VAK_MSVCUndefined;
966 
967  // FIXME: In C++11, these cases are conditionally-supported, meaning we're
968  // permitted to reject them. We should consider doing so.
969  return VAK_Undefined;
970 }
971 
973  // Don't allow one to pass an Objective-C interface to a vararg.
974  const QualType &Ty = E->getType();
975  VarArgKind VAK = isValidVarArgType(Ty);
976 
977  // Complain about passing non-POD types through varargs.
978  switch (VAK) {
979  case VAK_ValidInCXX11:
980  DiagRuntimeBehavior(
981  E->getBeginLoc(), nullptr,
982  PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
983  [[fallthrough]];
984  case VAK_Valid:
985  if (Ty->isRecordType()) {
986  // This is unlikely to be what the user intended. If the class has a
987  // 'c_str' member function, the user probably meant to call that.
988  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
989  PDiag(diag::warn_pass_class_arg_to_vararg)
990  << Ty << CT << hasCStrMethod(E) << ".c_str()");
991  }
992  break;
993 
994  case VAK_Undefined:
995  case VAK_MSVCUndefined:
996  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
997  PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
998  << getLangOpts().CPlusPlus11 << Ty << CT);
999  break;
1000 
1001  case VAK_Invalid:
1003  Diag(E->getBeginLoc(),
1004  diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1005  << Ty << CT;
1006  else if (Ty->isObjCObjectType())
1007  DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1008  PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1009  << Ty << CT);
1010  else
1011  Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1012  << isa<InitListExpr>(E) << Ty << CT;
1013  break;
1014  }
1015 }
1016 
1017 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1018 /// will create a trap if the resulting type is not a POD type.
1020  FunctionDecl *FDecl) {
1021  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1022  // Strip the unbridged-cast placeholder expression off, if applicable.
1023  if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1024  (CT == VariadicMethod ||
1025  (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1026  E = stripARCUnbridgedCast(E);
1027 
1028  // Otherwise, do normal placeholder checking.
1029  } else {
1030  ExprResult ExprRes = CheckPlaceholderExpr(E);
1031  if (ExprRes.isInvalid())
1032  return ExprError();
1033  E = ExprRes.get();
1034  }
1035  }
1036 
1037  ExprResult ExprRes = DefaultArgumentPromotion(E);
1038  if (ExprRes.isInvalid())
1039  return ExprError();
1040 
1041  // Copy blocks to the heap.
1042  if (ExprRes.get()->getType()->isBlockPointerType())
1043  maybeExtendBlockObject(ExprRes);
1044 
1045  E = ExprRes.get();
1046 
1047  // Diagnostics regarding non-POD argument types are
1048  // emitted along with format string checking in Sema::CheckFunctionCall().
1049  if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1050  // Turn this into a trap.
1051  CXXScopeSpec SS;
1052  SourceLocation TemplateKWLoc;
1053  UnqualifiedId Name;
1054  Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1055  E->getBeginLoc());
1056  ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1057  /*HasTrailingLParen=*/true,
1058  /*IsAddressOfOperand=*/false);
1059  if (TrapFn.isInvalid())
1060  return ExprError();
1061 
1062  ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1063  std::nullopt, E->getEndLoc());
1064  if (Call.isInvalid())
1065  return ExprError();
1066 
1067  ExprResult Comma =
1068  ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1069  if (Comma.isInvalid())
1070  return ExprError();
1071  return Comma.get();
1072  }
1073 
1074  if (!getLangOpts().CPlusPlus &&
1075  RequireCompleteType(E->getExprLoc(), E->getType(),
1076  diag::err_call_incomplete_argument))
1077  return ExprError();
1078 
1079  return E;
1080 }
1081 
1082 /// Converts an integer to complex float type. Helper function of
1083 /// UsualArithmeticConversions()
1084 ///
1085 /// \return false if the integer expression is an integer type and is
1086 /// successfully converted to the complex type.
1088  ExprResult &ComplexExpr,
1089  QualType IntTy,
1090  QualType ComplexTy,
1091  bool SkipCast) {
1092  if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1093  if (SkipCast) return false;
1094  if (IntTy->isIntegerType()) {
1095  QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1096  IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1097  IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1098  CK_FloatingRealToComplex);
1099  } else {
1100  assert(IntTy->isComplexIntegerType());
1101  IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1102  CK_IntegralComplexToFloatingComplex);
1103  }
1104  return false;
1105 }
1106 
1107 // This handles complex/complex, complex/float, or float/complex.
1108 // When both operands are complex, the shorter operand is converted to the
1109 // type of the longer, and that is the type of the result. This corresponds
1110 // to what is done when combining two real floating-point operands.
1111 // The fun begins when size promotion occur across type domains.
1112 // From H&S 6.3.4: When one operand is complex and the other is a real
1113 // floating-point type, the less precise type is converted, within it's
1114 // real or complex domain, to the precision of the other type. For example,
1115 // when combining a "long double" with a "double _Complex", the
1116 // "double _Complex" is promoted to "long double _Complex".
1118  QualType ShorterType,
1119  QualType LongerType,
1120  bool PromotePrecision) {
1121  bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1122  QualType Result =
1123  LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1124 
1125  if (PromotePrecision) {
1126  if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1127  Shorter =
1128  S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1129  } else {
1130  if (LongerIsComplex)
1131  LongerType = LongerType->castAs<ComplexType>()->getElementType();
1132  Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1133  }
1134  }
1135  return Result;
1136 }
1137 
1138 /// Handle arithmetic conversion with complex types. Helper function of
1139 /// UsualArithmeticConversions()
1141  ExprResult &RHS, QualType LHSType,
1142  QualType RHSType, bool IsCompAssign) {
1143  // if we have an integer operand, the result is the complex type.
1144  if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1145  /*SkipCast=*/false))
1146  return LHSType;
1147  if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1148  /*SkipCast=*/IsCompAssign))
1149  return RHSType;
1150 
1151  // Compute the rank of the two types, regardless of whether they are complex.
1152  int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1153  if (Order < 0)
1154  // Promote the precision of the LHS if not an assignment.
1155  return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1156  /*PromotePrecision=*/!IsCompAssign);
1157  // Promote the precision of the RHS unless it is already the same as the LHS.
1158  return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1159  /*PromotePrecision=*/Order > 0);
1160 }
1161 
1162 /// Handle arithmetic conversion from integer to float. Helper function
1163 /// of UsualArithmeticConversions()
1165  ExprResult &IntExpr,
1166  QualType FloatTy, QualType IntTy,
1167  bool ConvertFloat, bool ConvertInt) {
1168  if (IntTy->isIntegerType()) {
1169  if (ConvertInt)
1170  // Convert intExpr to the lhs floating point type.
1171  IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1172  CK_IntegralToFloating);
1173  return FloatTy;
1174  }
1175 
1176  // Convert both sides to the appropriate complex float.
1177  assert(IntTy->isComplexIntegerType());
1178  QualType result = S.Context.getComplexType(FloatTy);
1179 
1180  // _Complex int -> _Complex float
1181  if (ConvertInt)
1182  IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1183  CK_IntegralComplexToFloatingComplex);
1184 
1185  // float -> _Complex float
1186  if (ConvertFloat)
1187  FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1188  CK_FloatingRealToComplex);
1189 
1190  return result;
1191 }
1192 
1193 /// Handle arithmethic conversion with floating point types. Helper
1194 /// function of UsualArithmeticConversions()
1196  ExprResult &RHS, QualType LHSType,
1197  QualType RHSType, bool IsCompAssign) {
1198  bool LHSFloat = LHSType->isRealFloatingType();
1199  bool RHSFloat = RHSType->isRealFloatingType();
1200 
1201  // N1169 4.1.4: If one of the operands has a floating type and the other
1202  // operand has a fixed-point type, the fixed-point operand
1203  // is converted to the floating type [...]
1204  if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1205  if (LHSFloat)
1206  RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1207  else if (!IsCompAssign)
1208  LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1209  return LHSFloat ? LHSType : RHSType;
1210  }
1211 
1212  // If we have two real floating types, convert the smaller operand
1213  // to the bigger result.
1214  if (LHSFloat && RHSFloat) {
1215  int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1216  if (order > 0) {
1217  RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1218  return LHSType;
1219  }
1220 
1221  assert(order < 0 && "illegal float comparison");
1222  if (!IsCompAssign)
1223  LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1224  return RHSType;
1225  }
1226 
1227  if (LHSFloat) {
1228  // Half FP has to be promoted to float unless it is natively supported
1229  if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1230  LHSType = S.Context.FloatTy;
1231 
1232  return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1233  /*ConvertFloat=*/!IsCompAssign,
1234  /*ConvertInt=*/ true);
1235  }
1236  assert(RHSFloat);
1237  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1238  /*ConvertFloat=*/ true,
1239  /*ConvertInt=*/!IsCompAssign);
1240 }
1241 
1242 /// Diagnose attempts to convert between __float128, __ibm128 and
1243 /// long double if there is no support for such conversion.
1244 /// Helper function of UsualArithmeticConversions().
1245 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1246  QualType RHSType) {
1247  // No issue if either is not a floating point type.
1248  if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1249  return false;
1250 
1251  // No issue if both have the same 128-bit float semantics.
1252  auto *LHSComplex = LHSType->getAs<ComplexType>();
1253  auto *RHSComplex = RHSType->getAs<ComplexType>();
1254 
1255  QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1256  QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1257 
1258  const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1259  const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1260 
1261  if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1262  &RHSSem != &llvm::APFloat::IEEEquad()) &&
1263  (&LHSSem != &llvm::APFloat::IEEEquad() ||
1264  &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1265  return false;
1266 
1267  return true;
1268 }
1269 
1270 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1271 
1272 namespace {
1273 /// These helper callbacks are placed in an anonymous namespace to
1274 /// permit their use as function template parameters.
1275 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1276  return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1277 }
1278 
1279 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1280  return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1281  CK_IntegralComplexCast);
1282 }
1283 }
1284 
1285 /// Handle integer arithmetic conversions. Helper function of
1286 /// UsualArithmeticConversions()
1287 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1289  ExprResult &RHS, QualType LHSType,
1290  QualType RHSType, bool IsCompAssign) {
1291  // The rules for this case are in C99 6.3.1.8
1292  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1293  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1294  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1295  if (LHSSigned == RHSSigned) {
1296  // Same signedness; use the higher-ranked type
1297  if (order >= 0) {
1298  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1299  return LHSType;
1300  } else if (!IsCompAssign)
1301  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1302  return RHSType;
1303  } else if (order != (LHSSigned ? 1 : -1)) {
1304  // The unsigned type has greater than or equal rank to the
1305  // signed type, so use the unsigned type
1306  if (RHSSigned) {
1307  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1308  return LHSType;
1309  } else if (!IsCompAssign)
1310  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1311  return RHSType;
1312  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1313  // The two types are different widths; if we are here, that
1314  // means the signed type is larger than the unsigned type, so
1315  // use the signed type.
1316  if (LHSSigned) {
1317  RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1318  return LHSType;
1319  } else if (!IsCompAssign)
1320  LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1321  return RHSType;
1322  } else {
1323  // The signed type is higher-ranked than the unsigned type,
1324  // but isn't actually any bigger (like unsigned int and long
1325  // on most 32-bit systems). Use the unsigned type corresponding
1326  // to the signed type.
1327  QualType result =
1328  S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1329  RHS = (*doRHSCast)(S, RHS.get(), result);
1330  if (!IsCompAssign)
1331  LHS = (*doLHSCast)(S, LHS.get(), result);
1332  return result;
1333  }
1334 }
1335 
1336 /// Handle conversions with GCC complex int extension. Helper function
1337 /// of UsualArithmeticConversions()
1339  ExprResult &RHS, QualType LHSType,
1340  QualType RHSType,
1341  bool IsCompAssign) {
1342  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1343  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1344 
1345  if (LHSComplexInt && RHSComplexInt) {
1346  QualType LHSEltType = LHSComplexInt->getElementType();
1347  QualType RHSEltType = RHSComplexInt->getElementType();
1348  QualType ScalarType =
1349  handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1350  (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1351 
1352  return S.Context.getComplexType(ScalarType);
1353  }
1354 
1355  if (LHSComplexInt) {
1356  QualType LHSEltType = LHSComplexInt->getElementType();
1357  QualType ScalarType =
1358  handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1359  (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1360  QualType ComplexType = S.Context.getComplexType(ScalarType);
1361  RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1362  CK_IntegralRealToComplex);
1363 
1364  return ComplexType;
1365  }
1366 
1367  assert(RHSComplexInt);
1368 
1369  QualType RHSEltType = RHSComplexInt->getElementType();
1370  QualType ScalarType =
1371  handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1372  (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1373  QualType ComplexType = S.Context.getComplexType(ScalarType);
1374 
1375  if (!IsCompAssign)
1376  LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1377  CK_IntegralRealToComplex);
1378  return ComplexType;
1379 }
1380 
1381 /// Return the rank of a given fixed point or integer type. The value itself
1382 /// doesn't matter, but the values must be increasing with proper increasing
1383 /// rank as described in N1169 4.1.1.
1384 static unsigned GetFixedPointRank(QualType Ty) {
1385  const auto *BTy = Ty->getAs<BuiltinType>();
1386  assert(BTy && "Expected a builtin type.");
1387 
1388  switch (BTy->getKind()) {
1389  case BuiltinType::ShortFract:
1390  case BuiltinType::UShortFract:
1391  case BuiltinType::SatShortFract:
1392  case BuiltinType::SatUShortFract:
1393  return 1;
1394  case BuiltinType::Fract:
1395  case BuiltinType::UFract:
1396  case BuiltinType::SatFract:
1397  case BuiltinType::SatUFract:
1398  return 2;
1399  case BuiltinType::LongFract:
1400  case BuiltinType::ULongFract:
1401  case BuiltinType::SatLongFract:
1402  case BuiltinType::SatULongFract:
1403  return 3;
1404  case BuiltinType::ShortAccum:
1405  case BuiltinType::UShortAccum:
1406  case BuiltinType::SatShortAccum:
1407  case BuiltinType::SatUShortAccum:
1408  return 4;
1409  case BuiltinType::Accum:
1410  case BuiltinType::UAccum:
1411  case BuiltinType::SatAccum:
1412  case BuiltinType::SatUAccum:
1413  return 5;
1414  case BuiltinType::LongAccum:
1415  case BuiltinType::ULongAccum:
1416  case BuiltinType::SatLongAccum:
1417  case BuiltinType::SatULongAccum:
1418  return 6;
1419  default:
1420  if (BTy->isInteger())
1421  return 0;
1422  llvm_unreachable("Unexpected fixed point or integer type");
1423  }
1424 }
1425 
1426 /// handleFixedPointConversion - Fixed point operations between fixed
1427 /// point types and integers or other fixed point types do not fall under
1428 /// usual arithmetic conversion since these conversions could result in loss
1429 /// of precsision (N1169 4.1.4). These operations should be calculated with
1430 /// the full precision of their result type (N1169 4.1.6.2.1).
1432  QualType RHSTy) {
1433  assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1434  "Expected at least one of the operands to be a fixed point type");
1435  assert((LHSTy->isFixedPointOrIntegerType() ||
1436  RHSTy->isFixedPointOrIntegerType()) &&
1437  "Special fixed point arithmetic operation conversions are only "
1438  "applied to ints or other fixed point types");
1439 
1440  // If one operand has signed fixed-point type and the other operand has
1441  // unsigned fixed-point type, then the unsigned fixed-point operand is
1442  // converted to its corresponding signed fixed-point type and the resulting
1443  // type is the type of the converted operand.
1444  if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1446  else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1448 
1449  // The result type is the type with the highest rank, whereby a fixed-point
1450  // conversion rank is always greater than an integer conversion rank; if the
1451  // type of either of the operands is a saturating fixedpoint type, the result
1452  // type shall be the saturating fixed-point type corresponding to the type
1453  // with the highest rank; the resulting value is converted (taking into
1454  // account rounding and overflow) to the precision of the resulting type.
1455  // Same ranks between signed and unsigned types are resolved earlier, so both
1456  // types are either signed or both unsigned at this point.
1457  unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1458  unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1459 
1460  QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1461 
1462  if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1463  ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1464 
1465  return ResultTy;
1466 }
1467 
1468 /// Check that the usual arithmetic conversions can be performed on this pair of
1469 /// expressions that might be of enumeration type.
1470 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1471  SourceLocation Loc,
1472  Sema::ArithConvKind ACK) {
1473  // C++2a [expr.arith.conv]p1:
1474  // If one operand is of enumeration type and the other operand is of a
1475  // different enumeration type or a floating-point type, this behavior is
1476  // deprecated ([depr.arith.conv.enum]).
1477  //
1478  // Warn on this in all language modes. Produce a deprecation warning in C++20.
1479  // Eventually we will presumably reject these cases (in C++23 onwards?).
1480  QualType L = LHS->getType(), R = RHS->getType();
1481  bool LEnum = L->isUnscopedEnumerationType(),
1482  REnum = R->isUnscopedEnumerationType();
1483  bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1484  if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1485  (REnum && L->isFloatingType())) {
1486  S.Diag(Loc, S.getLangOpts().CPlusPlus20
1487  ? diag::warn_arith_conv_enum_float_cxx20
1488  : diag::warn_arith_conv_enum_float)
1489  << LHS->getSourceRange() << RHS->getSourceRange()
1490  << (int)ACK << LEnum << L << R;
1491  } else if (!IsCompAssign && LEnum && REnum &&
1492  !S.Context.hasSameUnqualifiedType(L, R)) {
1493  unsigned DiagID;
1494  if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1495  !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1496  // If either enumeration type is unnamed, it's less likely that the
1497  // user cares about this, but this situation is still deprecated in
1498  // C++2a. Use a different warning group.
1499  DiagID = S.getLangOpts().CPlusPlus20
1500  ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1501  : diag::warn_arith_conv_mixed_anon_enum_types;
1502  } else if (ACK == Sema::ACK_Conditional) {
1503  // Conditional expressions are separated out because they have
1504  // historically had a different warning flag.
1505  DiagID = S.getLangOpts().CPlusPlus20
1506  ? diag::warn_conditional_mixed_enum_types_cxx20
1507  : diag::warn_conditional_mixed_enum_types;
1508  } else if (ACK == Sema::ACK_Comparison) {
1509  // Comparison expressions are separated out because they have
1510  // historically had a different warning flag.
1511  DiagID = S.getLangOpts().CPlusPlus20
1512  ? diag::warn_comparison_mixed_enum_types_cxx20
1513  : diag::warn_comparison_mixed_enum_types;
1514  } else {
1515  DiagID = S.getLangOpts().CPlusPlus20
1516  ? diag::warn_arith_conv_mixed_enum_types_cxx20
1517  : diag::warn_arith_conv_mixed_enum_types;
1518  }
1519  S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1520  << (int)ACK << L << R;
1521  }
1522 }
1523 
1524 /// UsualArithmeticConversions - Performs various conversions that are common to
1525 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1526 /// routine returns the first non-arithmetic type found. The client is
1527 /// responsible for emitting appropriate error diagnostics.
1529  SourceLocation Loc,
1530  ArithConvKind ACK) {
1531  checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1532 
1533  if (ACK != ACK_CompAssign) {
1534  LHS = UsualUnaryConversions(LHS.get());
1535  if (LHS.isInvalid())
1536  return QualType();
1537  }
1538 
1539  RHS = UsualUnaryConversions(RHS.get());
1540  if (RHS.isInvalid())
1541  return QualType();
1542 
1543  // For conversion purposes, we ignore any qualifiers.
1544  // For example, "const float" and "float" are equivalent.
1545  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1546  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1547 
1548  // For conversion purposes, we ignore any atomic qualifier on the LHS.
1549  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1550  LHSType = AtomicLHS->getValueType();
1551 
1552  // If both types are identical, no conversion is needed.
1553  if (Context.hasSameType(LHSType, RHSType))
1554  return Context.getCommonSugaredType(LHSType, RHSType);
1555 
1556  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1557  // The caller can deal with this (e.g. pointer + int).
1558  if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1559  return QualType();
1560 
1561  // Apply unary and bitfield promotions to the LHS's type.
1562  QualType LHSUnpromotedType = LHSType;
1563  if (Context.isPromotableIntegerType(LHSType))
1564  LHSType = Context.getPromotedIntegerType(LHSType);
1565  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1566  if (!LHSBitfieldPromoteTy.isNull())
1567  LHSType = LHSBitfieldPromoteTy;
1568  if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1569  LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1570 
1571  // If both types are identical, no conversion is needed.
1572  if (Context.hasSameType(LHSType, RHSType))
1573  return Context.getCommonSugaredType(LHSType, RHSType);
1574 
1575  // At this point, we have two different arithmetic types.
1576 
1577  // Diagnose attempts to convert between __ibm128, __float128 and long double
1578  // where such conversions currently can't be handled.
1579  if (unsupportedTypeConversion(*this, LHSType, RHSType))
1580  return QualType();
1581 
1582  // Handle complex types first (C99 6.3.1.8p1).
1583  if (LHSType->isComplexType() || RHSType->isComplexType())
1584  return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1585  ACK == ACK_CompAssign);
1586 
1587  // Now handle "real" floating types (i.e. float, double, long double).
1588  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1589  return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1590  ACK == ACK_CompAssign);
1591 
1592  // Handle GCC complex int extension.
1593  if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1594  return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1595  ACK == ACK_CompAssign);
1596 
1597  if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1598  return handleFixedPointConversion(*this, LHSType, RHSType);
1599 
1600  // Finally, we have two differing integer types.
1601  return handleIntegerConversion<doIntegralCast, doIntegralCast>
1602  (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1603 }
1604 
1605 //===----------------------------------------------------------------------===//
1606 // Semantic Analysis for various Expression Types
1607 //===----------------------------------------------------------------------===//
1608 
1609 
1610 ExprResult
1612  SourceLocation DefaultLoc,
1613  SourceLocation RParenLoc,
1614  Expr *ControllingExpr,
1615  ArrayRef<ParsedType> ArgTypes,
1616  ArrayRef<Expr *> ArgExprs) {
1617  unsigned NumAssocs = ArgTypes.size();
1618  assert(NumAssocs == ArgExprs.size());
1619 
1620  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1621  for (unsigned i = 0; i < NumAssocs; ++i) {
1622  if (ArgTypes[i])
1623  (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1624  else
1625  Types[i] = nullptr;
1626  }
1627 
1628  ExprResult ER =
1629  CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, ControllingExpr,
1630  llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1631  delete [] Types;
1632  return ER;
1633 }
1634 
1635 ExprResult
1637  SourceLocation DefaultLoc,
1638  SourceLocation RParenLoc,
1639  Expr *ControllingExpr,
1641  ArrayRef<Expr *> Exprs) {
1642  unsigned NumAssocs = Types.size();
1643  assert(NumAssocs == Exprs.size());
1644 
1645  // Decay and strip qualifiers for the controlling expression type, and handle
1646  // placeholder type replacement. See committee discussion from WG14 DR423.
1647  {
1650  ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1651  if (R.isInvalid())
1652  return ExprError();
1653  ControllingExpr = R.get();
1654  }
1655 
1656  bool TypeErrorFound = false,
1657  IsResultDependent = ControllingExpr->isTypeDependent(),
1658  ContainsUnexpandedParameterPack
1659  = ControllingExpr->containsUnexpandedParameterPack();
1660 
1661  // The controlling expression is an unevaluated operand, so side effects are
1662  // likely unintended.
1663  if (!inTemplateInstantiation() && !IsResultDependent &&
1664  ControllingExpr->HasSideEffects(Context, false))
1665  Diag(ControllingExpr->getExprLoc(),
1666  diag::warn_side_effects_unevaluated_context);
1667 
1668  for (unsigned i = 0; i < NumAssocs; ++i) {
1669  if (Exprs[i]->containsUnexpandedParameterPack())
1670  ContainsUnexpandedParameterPack = true;
1671 
1672  if (Types[i]) {
1673  if (Types[i]->getType()->containsUnexpandedParameterPack())
1674  ContainsUnexpandedParameterPack = true;
1675 
1676  if (Types[i]->getType()->isDependentType()) {
1677  IsResultDependent = true;
1678  } else {
1679  // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1680  // complete object type other than a variably modified type."
1681  unsigned D = 0;
1682  if (Types[i]->getType()->isIncompleteType())
1683  D = diag::err_assoc_type_incomplete;
1684  else if (!Types[i]->getType()->isObjectType())
1685  D = diag::err_assoc_type_nonobject;
1686  else if (Types[i]->getType()->isVariablyModifiedType())
1687  D = diag::err_assoc_type_variably_modified;
1688  else {
1689  // Because the controlling expression undergoes lvalue conversion,
1690  // array conversion, and function conversion, an association which is
1691  // of array type, function type, or is qualified can never be
1692  // reached. We will warn about this so users are less surprised by
1693  // the unreachable association. However, we don't have to handle
1694  // function types; that's not an object type, so it's handled above.
1695  //
1696  // The logic is somewhat different for C++ because C++ has different
1697  // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1698  // If T is a non-class type, the type of the prvalue is the cv-
1699  // unqualified version of T. Otherwise, the type of the prvalue is T.
1700  // The result of these rules is that all qualified types in an
1701  // association in C are unreachable, and in C++, only qualified non-
1702  // class types are unreachable.
1703  unsigned Reason = 0;
1704  QualType QT = Types[i]->getType();
1705  if (QT->isArrayType())
1706  Reason = 1;
1707  else if (QT.hasQualifiers() &&
1708  (!LangOpts.CPlusPlus || !QT->isRecordType()))
1709  Reason = 2;
1710 
1711  if (Reason)
1712  Diag(Types[i]->getTypeLoc().getBeginLoc(),
1713  diag::warn_unreachable_association)
1714  << QT << (Reason - 1);
1715  }
1716 
1717  if (D != 0) {
1718  Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1719  << Types[i]->getTypeLoc().getSourceRange()
1720  << Types[i]->getType();
1721  TypeErrorFound = true;
1722  }
1723 
1724  // C11 6.5.1.1p2 "No two generic associations in the same generic
1725  // selection shall specify compatible types."
1726  for (unsigned j = i+1; j < NumAssocs; ++j)
1727  if (Types[j] && !Types[j]->getType()->isDependentType() &&
1728  Context.typesAreCompatible(Types[i]->getType(),
1729  Types[j]->getType())) {
1730  Diag(Types[j]->getTypeLoc().getBeginLoc(),
1731  diag::err_assoc_compatible_types)
1732  << Types[j]->getTypeLoc().getSourceRange()
1733  << Types[j]->getType()
1734  << Types[i]->getType();
1735  Diag(Types[i]->getTypeLoc().getBeginLoc(),
1736  diag::note_compat_assoc)
1737  << Types[i]->getTypeLoc().getSourceRange()
1738  << Types[i]->getType();
1739  TypeErrorFound = true;
1740  }
1741  }
1742  }
1743  }
1744  if (TypeErrorFound)
1745  return ExprError();
1746 
1747  // If we determined that the generic selection is result-dependent, don't
1748  // try to compute the result expression.
1749  if (IsResultDependent)
1750  return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1751  Exprs, DefaultLoc, RParenLoc,
1752  ContainsUnexpandedParameterPack);
1753 
1754  SmallVector<unsigned, 1> CompatIndices;
1755  unsigned DefaultIndex = -1U;
1756  // Look at the canonical type of the controlling expression in case it was a
1757  // deduced type like __auto_type. However, when issuing diagnostics, use the
1758  // type the user wrote in source rather than the canonical one.
1759  for (unsigned i = 0; i < NumAssocs; ++i) {
1760  if (!Types[i])
1761  DefaultIndex = i;
1762  else if (Context.typesAreCompatible(
1763  ControllingExpr->getType().getCanonicalType(),
1764  Types[i]->getType()))
1765  CompatIndices.push_back(i);
1766  }
1767 
1768  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1769  // type compatible with at most one of the types named in its generic
1770  // association list."
1771  if (CompatIndices.size() > 1) {
1772  // We strip parens here because the controlling expression is typically
1773  // parenthesized in macro definitions.
1774  ControllingExpr = ControllingExpr->IgnoreParens();
1775  Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1776  << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1777  << (unsigned)CompatIndices.size();
1778  for (unsigned I : CompatIndices) {
1779  Diag(Types[I]->getTypeLoc().getBeginLoc(),
1780  diag::note_compat_assoc)
1781  << Types[I]->getTypeLoc().getSourceRange()
1782  << Types[I]->getType();
1783  }
1784  return ExprError();
1785  }
1786 
1787  // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1788  // its controlling expression shall have type compatible with exactly one of
1789  // the types named in its generic association list."
1790  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1791  // We strip parens here because the controlling expression is typically
1792  // parenthesized in macro definitions.
1793  ControllingExpr = ControllingExpr->IgnoreParens();
1794  Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1795  << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1796  return ExprError();
1797  }
1798 
1799  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1800  // type name that is compatible with the type of the controlling expression,
1801  // then the result expression of the generic selection is the expression
1802  // in that generic association. Otherwise, the result expression of the
1803  // generic selection is the expression in the default generic association."
1804  unsigned ResultIndex =
1805  CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1806 
1808  Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1809  ContainsUnexpandedParameterPack, ResultIndex);
1810 }
1811 
1812 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1813 /// location of the token and the offset of the ud-suffix within it.
1815  unsigned Offset) {
1817  S.getLangOpts());
1818 }
1819 
1820 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1821 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1823  IdentifierInfo *UDSuffix,
1824  SourceLocation UDSuffixLoc,
1825  ArrayRef<Expr*> Args,
1826  SourceLocation LitEndLoc) {
1827  assert(Args.size() <= 2 && "too many arguments for literal operator");
1828 
1829  QualType ArgTy[2];
1830  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1831  ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1832  if (ArgTy[ArgIdx]->isArrayType())
1833  ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1834  }
1835 
1836  DeclarationName OpName =
1838  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1839  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1840 
1841  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1842  if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1843  /*AllowRaw*/ false, /*AllowTemplate*/ false,
1844  /*AllowStringTemplatePack*/ false,
1845  /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1846  return ExprError();
1847 
1848  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1849 }
1850 
1851 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1852 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1853 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1854 /// multiple tokens. However, the common case is that StringToks points to one
1855 /// string.
1856 ///
1857 ExprResult
1859  assert(!StringToks.empty() && "Must have at least one string!");
1860 
1861  StringLiteralParser Literal(StringToks, PP);
1862  if (Literal.hadError)
1863  return ExprError();
1864 
1865  SmallVector<SourceLocation, 4> StringTokLocs;
1866  for (const Token &Tok : StringToks)
1867  StringTokLocs.push_back(Tok.getLocation());
1868 
1869  QualType CharTy = Context.CharTy;
1871  if (Literal.isWide()) {
1872  CharTy = Context.getWideCharType();
1874  } else if (Literal.isUTF8()) {
1875  if (getLangOpts().Char8)
1876  CharTy = Context.Char8Ty;
1878  } else if (Literal.isUTF16()) {
1879  CharTy = Context.Char16Ty;
1881  } else if (Literal.isUTF32()) {
1882  CharTy = Context.Char32Ty;
1884  } else if (Literal.isPascal()) {
1885  CharTy = Context.UnsignedCharTy;
1886  }
1887 
1888  // Warn on initializing an array of char from a u8 string literal; this
1889  // becomes ill-formed in C++2a.
1890  if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1891  !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1892  Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1893 
1894  // Create removals for all 'u8' prefixes in the string literal(s). This
1895  // ensures C++2a compatibility (but may change the program behavior when
1896  // built by non-Clang compilers for which the execution character set is
1897  // not always UTF-8).
1898  auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1899  SourceLocation RemovalDiagLoc;
1900  for (const Token &Tok : StringToks) {
1901  if (Tok.getKind() == tok::utf8_string_literal) {
1902  if (RemovalDiagLoc.isInvalid())
1903  RemovalDiagLoc = Tok.getLocation();
1905  Tok.getLocation(),
1906  Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1907  getSourceManager(), getLangOpts())));
1908  }
1909  }
1910  Diag(RemovalDiagLoc, RemovalDiag);
1911  }
1912 
1913  QualType StrTy =
1914  Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1915 
1916  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1917  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1918  Kind, Literal.Pascal, StrTy,
1919  &StringTokLocs[0],
1920  StringTokLocs.size());
1921  if (Literal.getUDSuffix().empty())
1922  return Lit;
1923 
1924  // We're building a user-defined literal.
1925  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1926  SourceLocation UDSuffixLoc =
1927  getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1928  Literal.getUDSuffixOffset());
1929 
1930  // Make sure we're allowed user-defined literals here.
1931  if (!UDLScope)
1932  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1933 
1934  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1935  // operator "" X (str, len)
1936  QualType SizeType = Context.getSizeType();
1937 
1938  DeclarationName OpName =
1939  Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1940  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1941  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1942 
1943  QualType ArgTy[] = {
1944  Context.getArrayDecayedType(StrTy), SizeType
1945  };
1946 
1947  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1948  switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1949  /*AllowRaw*/ false, /*AllowTemplate*/ true,
1950  /*AllowStringTemplatePack*/ true,
1951  /*DiagnoseMissing*/ true, Lit)) {
1952 
1953  case LOLR_Cooked: {
1954  llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1955  IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1956  StringTokLocs[0]);
1957  Expr *Args[] = { Lit, LenArg };
1958 
1959  return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1960  }
1961 
1962  case LOLR_Template: {
1963  TemplateArgumentListInfo ExplicitArgs;
1964  TemplateArgument Arg(Lit);
1965  TemplateArgumentLocInfo ArgInfo(Lit);
1966  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1967  return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
1968  StringTokLocs.back(), &ExplicitArgs);
1969  }
1970 
1971  case LOLR_StringTemplatePack: {
1972  TemplateArgumentListInfo ExplicitArgs;
1973 
1974  unsigned CharBits = Context.getIntWidth(CharTy);
1975  bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1976  llvm::APSInt Value(CharBits, CharIsUnsigned);
1977 
1978  TemplateArgument TypeArg(CharTy);
1979  TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1980  ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1981 
1982  for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1983  Value = Lit->getCodeUnit(I);
1984  TemplateArgument Arg(Context, Value, CharTy);
1985  TemplateArgumentLocInfo ArgInfo;
1986  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1987  }
1988  return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
1989  StringTokLocs.back(), &ExplicitArgs);
1990  }
1991  case LOLR_Raw:
1992  case LOLR_ErrorNoDiagnostic:
1993  llvm_unreachable("unexpected literal operator lookup result");
1994  case LOLR_Error:
1995  return ExprError();
1996  }
1997  llvm_unreachable("unexpected literal operator lookup result");
1998 }
1999 
2000 DeclRefExpr *
2002  SourceLocation Loc,
2003  const CXXScopeSpec *SS) {
2004  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2005  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2006 }
2007 
2008 DeclRefExpr *
2010  const DeclarationNameInfo &NameInfo,
2011  const CXXScopeSpec *SS, NamedDecl *FoundD,
2012  SourceLocation TemplateKWLoc,
2013  const TemplateArgumentListInfo *TemplateArgs) {
2015  SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2016  return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2017  TemplateArgs);
2018 }
2019 
2020 // CUDA/HIP: Check whether a captured reference variable is referencing a
2021 // host variable in a device or host device lambda.
2023  VarDecl *VD) {
2024  if (!S.getLangOpts().CUDA || !VD->hasInit())
2025  return false;
2026  assert(VD->getType()->isReferenceType());
2027 
2028  // Check whether the reference variable is referencing a host variable.
2029  auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2030  if (!DRE)
2031  return false;
2032  auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2033  if (!Referee || !Referee->hasGlobalStorage() ||
2034  Referee->hasAttr<CUDADeviceAttr>())
2035  return false;
2036 
2037  // Check whether the current function is a device or host device lambda.
2038  // Check whether the reference variable is a capture by getDeclContext()
2039  // since refersToEnclosingVariableOrCapture() is not ready at this point.
2040  auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2041  if (MD && MD->getParent()->isLambda() &&
2042  MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2043  VD->getDeclContext() != MD)
2044  return true;
2045 
2046  return false;
2047 }
2048 
2050  // A declaration named in an unevaluated operand never constitutes an odr-use.
2051  if (isUnevaluatedContext())
2052  return NOUR_Unevaluated;
2053 
2054  // C++2a [basic.def.odr]p4:
2055  // A variable x whose name appears as a potentially-evaluated expression e
2056  // is odr-used by e unless [...] x is a reference that is usable in
2057  // constant expressions.
2058  // CUDA/HIP:
2059  // If a reference variable referencing a host variable is captured in a
2060  // device or host device lambda, the value of the referee must be copied
2061  // to the capture and the reference variable must be treated as odr-use
2062  // since the value of the referee is not known at compile time and must
2063  // be loaded from the captured.
2064  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2065  if (VD->getType()->isReferenceType() &&
2066  !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2068  VD->isUsableInConstantExpressions(Context))
2069  return NOUR_Constant;
2070  }
2071 
2072  // All remaining non-variable cases constitute an odr-use. For variables, we
2073  // need to wait and see how the expression is used.
2074  return NOUR_None;
2075 }
2076 
2077 /// BuildDeclRefExpr - Build an expression that references a
2078 /// declaration that does not require a closure capture.
2079 DeclRefExpr *
2081  const DeclarationNameInfo &NameInfo,
2082  NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2083  SourceLocation TemplateKWLoc,
2084  const TemplateArgumentListInfo *TemplateArgs) {
2085  bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2086  NeedToCaptureVariable(D, NameInfo.getLoc());
2087 
2089  Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2090  VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2091  MarkDeclRefReferenced(E);
2092 
2093  // C++ [except.spec]p17:
2094  // An exception-specification is considered to be needed when:
2095  // - in an expression, the function is the unique lookup result or
2096  // the selected member of a set of overloaded functions.
2097  //
2098  // We delay doing this until after we've built the function reference and
2099  // marked it as used so that:
2100  // a) if the function is defaulted, we get errors from defining it before /
2101  // instead of errors from computing its exception specification, and
2102  // b) if the function is a defaulted comparison, we can use the body we
2103  // build when defining it as input to the exception specification
2104  // computation rather than computing a new body.
2105  if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2106  if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2107  if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2108  E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2109  }
2110  }
2111 
2112  if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2113  Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2114  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2115  getCurFunction()->recordUseOfWeak(E);
2116 
2117  FieldDecl *FD = dyn_cast<FieldDecl>(D);
2118  if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2119  FD = IFD->getAnonField();
2120  if (FD) {
2121  UnusedPrivateFields.remove(FD);
2122  // Just in case we're building an illegal pointer-to-member.
2123  if (FD->isBitField())
2125  }
2126 
2127  // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2128  // designates a bit-field.
2129  if (auto *BD = dyn_cast<BindingDecl>(D))
2130  if (auto *BE = BD->getBinding())
2131  E->setObjectKind(BE->getObjectKind());
2132 
2133  return E;
2134 }
2135 
2136 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2137 /// possibly a list of template arguments.
2138 ///
2139 /// If this produces template arguments, it is permitted to call
2140 /// DecomposeTemplateName.
2141 ///
2142 /// This actually loses a lot of source location information for
2143 /// non-standard name kinds; we should consider preserving that in
2144 /// some way.
2145 void
2147  TemplateArgumentListInfo &Buffer,
2148  DeclarationNameInfo &NameInfo,
2149  const TemplateArgumentListInfo *&TemplateArgs) {
2150  if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2151  Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2152  Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2153 
2154  ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2155  Id.TemplateId->NumArgs);
2156  translateTemplateArguments(TemplateArgsPtr, Buffer);
2157 
2158  TemplateName TName = Id.TemplateId->Template.get();
2159  SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2160  NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2161  TemplateArgs = &Buffer;
2162  } else {
2163  NameInfo = GetNameFromUnqualifiedId(Id);
2164  TemplateArgs = nullptr;
2165  }
2166 }
2167 
2169  const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2170  DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2171  unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2172  DeclContext *Ctx =
2173  SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2174  if (!TC) {
2175  // Emit a special diagnostic for failed member lookups.
2176  // FIXME: computing the declaration context might fail here (?)
2177  if (Ctx)
2178  SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2179  << SS.getRange();
2180  else
2181  SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2182  return;
2183  }
2184 
2185  std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2186  bool DroppedSpecifier =
2187  TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2188  unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2189  ? diag::note_implicit_param_decl
2190  : diag::note_previous_decl;
2191  if (!Ctx)
2192  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2193  SemaRef.PDiag(NoteID));
2194  else
2195  SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2196  << Typo << Ctx << DroppedSpecifier
2197  << SS.getRange(),
2198  SemaRef.PDiag(NoteID));
2199 }
2200 
2201 /// Diagnose a lookup that found results in an enclosing class during error
2202 /// recovery. This usually indicates that the results were found in a dependent
2203 /// base class that could not be searched as part of a template definition.
2204 /// Always issues a diagnostic (though this may be only a warning in MS
2205 /// compatibility mode).
2206 ///
2207 /// Return \c true if the error is unrecoverable, or \c false if the caller
2208 /// should attempt to recover using these lookup results.
2210  // During a default argument instantiation the CurContext points
2211  // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2212  // function parameter list, hence add an explicit check.
2213  bool isDefaultArgument =
2214  !CodeSynthesisContexts.empty() &&
2215  CodeSynthesisContexts.back().Kind ==
2216  CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2217  CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2218  bool isInstance = CurMethod && CurMethod->isInstance() &&
2219  R.getNamingClass() == CurMethod->getParent() &&
2220  !isDefaultArgument;
2221 
2222  // There are two ways we can find a class-scope declaration during template
2223  // instantiation that we did not find in the template definition: if it is a
2224  // member of a dependent base class, or if it is declared after the point of
2225  // use in the same class. Distinguish these by comparing the class in which
2226  // the member was found to the naming class of the lookup.
2227  unsigned DiagID = diag::err_found_in_dependent_base;
2228  unsigned NoteID = diag::note_member_declared_at;
2230  DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2231  : diag::err_found_later_in_class;
2232  } else if (getLangOpts().MSVCCompat) {
2233  DiagID = diag::ext_found_in_dependent_base;
2234  NoteID = diag::note_dependent_member_use;
2235  }
2236 
2237  if (isInstance) {
2238  // Give a code modification hint to insert 'this->'.
2239  Diag(R.getNameLoc(), DiagID)
2240  << R.getLookupName()
2241  << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2242  CheckCXXThisCapture(R.getNameLoc());
2243  } else {
2244  // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2245  // they're not shadowed).
2246  Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2247  }
2248 
2249  for (NamedDecl *D : R)
2250  Diag(D->getLocation(), NoteID);
2251 
2252  // Return true if we are inside a default argument instantiation
2253  // and the found name refers to an instance member function, otherwise
2254  // the caller will try to create an implicit member call and this is wrong
2255  // for default arguments.
2256  //
2257  // FIXME: Is this special case necessary? We could allow the caller to
2258  // diagnose this.
2259  if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2260  Diag(R.getNameLoc(), diag::err_member_call_without_object);
2261  return true;
2262  }
2263 
2264  // Tell the callee to try to recover.
2265  return false;
2266 }
2267 
2268 /// Diagnose an empty lookup.
2269 ///
2270 /// \return false if new lookup candidates were found
2273  TemplateArgumentListInfo *ExplicitTemplateArgs,
2274  ArrayRef<Expr *> Args, TypoExpr **Out) {
2275  DeclarationName Name = R.getLookupName();
2276 
2277  unsigned diagnostic = diag::err_undeclared_var_use;
2278  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2279  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2280  Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2281  Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2282  diagnostic = diag::err_undeclared_use;
2283  diagnostic_suggest = diag::err_undeclared_use_suggest;
2284  }
2285 
2286  // If the original lookup was an unqualified lookup, fake an
2287  // unqualified lookup. This is useful when (for example) the
2288  // original lookup would not have found something because it was a
2289  // dependent name.
2290  DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2291  while (DC) {
2292  if (isa<CXXRecordDecl>(DC)) {
2293  LookupQualifiedName(R, DC);
2294 
2295  if (!R.empty()) {
2296  // Don't give errors about ambiguities in this lookup.
2297  R.suppressDiagnostics();
2298 
2299  // If there's a best viable function among the results, only mention
2300  // that one in the notes.
2301  OverloadCandidateSet Candidates(R.getNameLoc(),
2303  AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2305  if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2306  OR_Success) {
2307  R.clear();
2308  R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2309  R.resolveKind();
2310  }
2311 
2312  return DiagnoseDependentMemberLookup(R);
2313  }
2314 
2315  R.clear();
2316  }
2317 
2318  DC = DC->getLookupParent();
2319  }
2320 
2321  // We didn't find anything, so try to correct for a typo.
2322  TypoCorrection Corrected;
2323  if (S && Out) {
2324  SourceLocation TypoLoc = R.getNameLoc();
2325  assert(!ExplicitTemplateArgs &&
2326  "Diagnosing an empty lookup with explicit template args!");
2327  *Out = CorrectTypoDelayed(
2328  R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2329  [=](const TypoCorrection &TC) {
2330  emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2331  diagnostic, diagnostic_suggest);
2332  },
2333  nullptr, CTK_ErrorRecovery);
2334  if (*Out)
2335  return true;
2336  } else if (S &&
2337  (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2338  S, &SS, CCC, CTK_ErrorRecovery))) {
2339  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2340  bool DroppedSpecifier =
2341  Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2342  R.setLookupName(Corrected.getCorrection());
2343 
2344  bool AcceptableWithRecovery = false;
2345  bool AcceptableWithoutRecovery = false;
2346  NamedDecl *ND = Corrected.getFoundDecl();
2347  if (ND) {
2348  if (Corrected.isOverloaded()) {
2352  for (NamedDecl *CD : Corrected) {
2353  if (FunctionTemplateDecl *FTD =
2354  dyn_cast<FunctionTemplateDecl>(CD))
2355  AddTemplateOverloadCandidate(
2356  FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2357  Args, OCS);
2358  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2359  if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2360  AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2361  Args, OCS);
2362  }
2363  switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2364  case OR_Success:
2365  ND = Best->FoundDecl;
2366  Corrected.setCorrectionDecl(ND);
2367  break;
2368  default:
2369  // FIXME: Arbitrarily pick the first declaration for the note.
2370  Corrected.setCorrectionDecl(ND);
2371  break;
2372  }
2373  }
2374  R.addDecl(ND);
2375  if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2376  CXXRecordDecl *Record = nullptr;
2377  if (Corrected.getCorrectionSpecifier()) {
2378  const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2379  Record = Ty->getAsCXXRecordDecl();
2380  }
2381  if (!Record)
2382  Record = cast<CXXRecordDecl>(
2383  ND->getDeclContext()->getRedeclContext());
2384  R.setNamingClass(Record);
2385  }
2386 
2387  auto *UnderlyingND = ND->getUnderlyingDecl();
2388  AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2389  isa<FunctionTemplateDecl>(UnderlyingND);
2390  // FIXME: If we ended up with a typo for a type name or
2391  // Objective-C class name, we're in trouble because the parser
2392  // is in the wrong place to recover. Suggest the typo
2393  // correction, but don't make it a fix-it since we're not going
2394  // to recover well anyway.
2395  AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2396  getAsTypeTemplateDecl(UnderlyingND) ||
2397  isa<ObjCInterfaceDecl>(UnderlyingND);
2398  } else {
2399  // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2400  // because we aren't able to recover.
2401  AcceptableWithoutRecovery = true;
2402  }
2403 
2404  if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2405  unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2406  ? diag::note_implicit_param_decl
2407  : diag::note_previous_decl;
2408  if (SS.isEmpty())
2409  diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2410  PDiag(NoteID), AcceptableWithRecovery);
2411  else
2412  diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2413  << Name << computeDeclContext(SS, false)
2414  << DroppedSpecifier << SS.getRange(),
2415  PDiag(NoteID), AcceptableWithRecovery);
2416 
2417  // Tell the callee whether to try to recover.
2418  return !AcceptableWithRecovery;
2419  }
2420  }
2421  R.clear();
2422 
2423  // Emit a special diagnostic for failed member lookups.
2424  // FIXME: computing the declaration context might fail here (?)
2425  if (!SS.isEmpty()) {
2426  Diag(R.getNameLoc(), diag::err_no_member)
2427  << Name << computeDeclContext(SS, false)
2428  << SS.getRange();
2429  return true;
2430  }
2431 
2432  // Give up, we can't recover.
2433  Diag(R.getNameLoc(), diagnostic) << Name;
2434  return true;
2435 }
2436 
2437 /// In Microsoft mode, if we are inside a template class whose parent class has
2438 /// dependent base classes, and we can't resolve an unqualified identifier, then
2439 /// assume the identifier is a member of a dependent base class. We can only
2440 /// recover successfully in static methods, instance methods, and other contexts
2441 /// where 'this' is available. This doesn't precisely match MSVC's
2442 /// instantiation model, but it's close enough.
2443 static Expr *
2445  DeclarationNameInfo &NameInfo,
2446  SourceLocation TemplateKWLoc,
2447  const TemplateArgumentListInfo *TemplateArgs) {
2448  // Only try to recover from lookup into dependent bases in static methods or
2449  // contexts where 'this' is available.
2450  QualType ThisType = S.getCurrentThisType();
2451  const CXXRecordDecl *RD = nullptr;
2452  if (!ThisType.isNull())
2453  RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2454  else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2455  RD = MD->getParent();
2456  if (!RD || !RD->hasAnyDependentBases())
2457  return nullptr;
2458 
2459  // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2460  // is available, suggest inserting 'this->' as a fixit.
2461  SourceLocation Loc = NameInfo.getLoc();
2462  auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2463  DB << NameInfo.getName() << RD;
2464 
2465  if (!ThisType.isNull()) {
2466  DB << FixItHint::CreateInsertion(Loc, "this->");
2468  Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2469  /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2470  /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2471  }
2472 
2473  // Synthesize a fake NNS that points to the derived class. This will
2474  // perform name lookup during template instantiation.
2475  CXXScopeSpec SS;
2476  auto *NNS =
2477  NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2478  SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2480  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2481  TemplateArgs);
2482 }
2483 
2484 ExprResult
2486  SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2487  bool HasTrailingLParen, bool IsAddressOfOperand,
2489  bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2490  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2491  "cannot be direct & operand and have a trailing lparen");
2492  if (SS.isInvalid())
2493  return ExprError();
2494 
2495  TemplateArgumentListInfo TemplateArgsBuffer;
2496 
2497  // Decompose the UnqualifiedId into the following data.
2498  DeclarationNameInfo NameInfo;
2499  const TemplateArgumentListInfo *TemplateArgs;
2500  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2501 
2502  DeclarationName Name = NameInfo.getName();
2503  IdentifierInfo *II = Name.getAsIdentifierInfo();
2504  SourceLocation NameLoc = NameInfo.getLoc();
2505 
2506  if (II && II->isEditorPlaceholder()) {
2507  // FIXME: When typed placeholders are supported we can create a typed
2508  // placeholder expression node.
2509  return ExprError();
2510  }
2511 
2512  // C++ [temp.dep.expr]p3:
2513  // An id-expression is type-dependent if it contains:
2514  // -- an identifier that was declared with a dependent type,
2515  // (note: handled after lookup)
2516  // -- a template-id that is dependent,
2517  // (note: handled in BuildTemplateIdExpr)
2518  // -- a conversion-function-id that specifies a dependent type,
2519  // -- a nested-name-specifier that contains a class-name that
2520  // names a dependent type.
2521  // Determine whether this is a member of an unknown specialization;
2522  // we need to handle these differently.
2523  bool DependentID = false;
2524  if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2525  Name.getCXXNameType()->isDependentType()) {
2526  DependentID = true;
2527  } else if (SS.isSet()) {
2528  if (DeclContext *DC = computeDeclContext(SS, false)) {
2529  if (RequireCompleteDeclContext(SS, DC))
2530  return ExprError();
2531  } else {
2532  DependentID = true;
2533  }
2534  }
2535 
2536  if (DependentID)
2537  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2538  IsAddressOfOperand, TemplateArgs);
2539 
2540  // Perform the required lookup.
2541  LookupResult R(*this, NameInfo,
2543  ? LookupObjCImplicitSelfParam
2544  : LookupOrdinaryName);
2545  if (TemplateKWLoc.isValid() || TemplateArgs) {
2546  // Lookup the template name again to correctly establish the context in
2547  // which it was found. This is really unfortunate as we already did the
2548  // lookup to determine that it was a template name in the first place. If
2549  // this becomes a performance hit, we can work harder to preserve those
2550  // results until we get here but it's likely not worth it.
2551  bool MemberOfUnknownSpecialization;
2552  AssumedTemplateKind AssumedTemplate;
2553  if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2554  MemberOfUnknownSpecialization, TemplateKWLoc,
2555  &AssumedTemplate))
2556  return ExprError();
2557 
2558  if (MemberOfUnknownSpecialization ||
2560  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2561  IsAddressOfOperand, TemplateArgs);
2562  } else {
2563  bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2564  LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2565 
2566  // If the result might be in a dependent base class, this is a dependent
2567  // id-expression.
2569  return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2570  IsAddressOfOperand, TemplateArgs);
2571 
2572  // If this reference is in an Objective-C method, then we need to do
2573  // some special Objective-C lookup, too.
2574  if (IvarLookupFollowUp) {
2575  ExprResult E(LookupInObjCMethod(R, S, II, true));
2576  if (E.isInvalid())
2577  return ExprError();
2578 
2579  if (Expr *Ex = E.getAs<Expr>())
2580  return Ex;
2581  }
2582  }
2583 
2584  if (R.isAmbiguous())
2585  return ExprError();
2586 
2587  // This could be an implicitly declared function reference if the language
2588  // mode allows it as a feature.
2589  if (R.empty() && HasTrailingLParen && II &&
2590  getLangOpts().implicitFunctionsAllowed()) {
2591  NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2592  if (D) R.addDecl(D);
2593  }
2594 
2595  // Determine whether this name might be a candidate for
2596  // argument-dependent lookup.
2597  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2598 
2599  if (R.empty() && !ADL) {
2600  if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2601  if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2602  TemplateKWLoc, TemplateArgs))
2603  return E;
2604  }
2605 
2606  // Don't diagnose an empty lookup for inline assembly.
2607  if (IsInlineAsmIdentifier)
2608  return ExprError();
2609 
2610  // If this name wasn't predeclared and if this is not a function
2611  // call, diagnose the problem.
2612  TypoExpr *TE = nullptr;
2613  DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2614  : nullptr);
2615  DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2616  assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2617  "Typo correction callback misconfigured");
2618  if (CCC) {
2619  // Make sure the callback knows what the typo being diagnosed is.
2620  CCC->setTypoName(II);
2621  if (SS.isValid())
2622  CCC->setTypoNNS(SS.getScopeRep());
2623  }
2624  // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2625  // a template name, but we happen to have always already looked up the name
2626  // before we get here if it must be a template name.
2627  if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2628  std::nullopt, &TE)) {
2629  if (TE && KeywordReplacement) {
2630  auto &State = getTypoExprState(TE);
2631  auto BestTC = State.Consumer->getNextCorrection();
2632  if (BestTC.isKeyword()) {
2633  auto *II = BestTC.getCorrectionAsIdentifierInfo();
2634  if (State.DiagHandler)
2635  State.DiagHandler(BestTC);
2636  KeywordReplacement->startToken();
2637  KeywordReplacement->setKind(II->getTokenID());
2638  KeywordReplacement->setIdentifierInfo(II);
2639  KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2640  // Clean up the state associated with the TypoExpr, since it has
2641  // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2642  clearDelayedTypo(TE);
2643  // Signal that a correction to a keyword was performed by returning a
2644  // valid-but-null ExprResult.
2645  return (Expr*)nullptr;
2646  }
2647  State.Consumer->resetCorrectionStream();
2648  }
2649  return TE ? TE : ExprError();
2650  }
2651 
2652  assert(!R.empty() &&
2653  "DiagnoseEmptyLookup returned false but added no results");
2654 
2655  // If we found an Objective-C instance variable, let
2656  // LookupInObjCMethod build the appropriate expression to
2657  // reference the ivar.
2658  if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2659  R.clear();
2660  ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2661  // In a hopelessly buggy code, Objective-C instance variable
2662  // lookup fails and no expression will be built to reference it.
2663  if (!E.isInvalid() && !E.get())
2664  return ExprError();
2665  return E;
2666  }
2667  }
2668 
2669  // This is guaranteed from this point on.
2670  assert(!R.empty() || ADL);
2671 
2672  // Check whether this might be a C++ implicit instance member access.
2673  // C++ [class.mfct.non-static]p3:
2674  // When an id-expression that is not part of a class member access
2675  // syntax and not used to form a pointer to member is used in the
2676  // body of a non-static member function of class X, if name lookup
2677  // resolves the name in the id-expression to a non-static non-type
2678  // member of some class C, the id-expression is transformed into a
2679  // class member access expression using (*this) as the
2680  // postfix-expression to the left of the . operator.
2681  //
2682  // But we don't actually need to do this for '&' operands if R
2683  // resolved to a function or overloaded function set, because the
2684  // expression is ill-formed if it actually works out to be a
2685  // non-static member function:
2686  //
2687  // C++ [expr.ref]p4:
2688  // Otherwise, if E1.E2 refers to a non-static member function. . .
2689  // [t]he expression can be used only as the left-hand operand of a
2690  // member function call.
2691  //
2692  // There are other safeguards against such uses, but it's important
2693  // to get this right here so that we don't end up making a
2694  // spuriously dependent expression if we're inside a dependent
2695  // instance method.
2696  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2697  bool MightBeImplicitMember;
2698  if (!IsAddressOfOperand)
2699  MightBeImplicitMember = true;
2700  else if (!SS.isEmpty())
2701  MightBeImplicitMember = false;
2702  else if (R.isOverloadedResult())
2703  MightBeImplicitMember = false;
2704  else if (R.isUnresolvableResult())
2705  MightBeImplicitMember = true;
2706  else
2707  MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2708  isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2709  isa<MSPropertyDecl>(R.getFoundDecl());
2710 
2711  if (MightBeImplicitMember)
2712  return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2713  R, TemplateArgs, S);
2714  }
2715 
2716  if (TemplateArgs || TemplateKWLoc.isValid()) {
2717 
2718  // In C++1y, if this is a variable template id, then check it
2719  // in BuildTemplateIdExpr().
2720  // The single lookup result must be a variable template declaration.
2721  if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2722  Id.TemplateId->Kind == TNK_Var_template) {
2723  assert(R.getAsSingle<VarTemplateDecl>() &&
2724  "There should only be one declaration found.");
2725  }
2726 
2727  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2728  }
2729 
2730  return BuildDeclarationNameExpr(SS, R, ADL);
2731 }
2732 
2733 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2734 /// declaration name, generally during template instantiation.
2735 /// There's a large number of things which don't need to be done along
2736 /// this path.
2738  CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2739  bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2740  if (NameInfo.getName().isDependentName())
2741  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2742  NameInfo, /*TemplateArgs=*/nullptr);
2743 
2744  DeclContext *DC = computeDeclContext(SS, false);
2745  if (!DC)
2746  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2747  NameInfo, /*TemplateArgs=*/nullptr);
2748 
2749  if (RequireCompleteDeclContext(SS, DC))
2750  return ExprError();
2751 
2752  LookupResult R(*this, NameInfo, LookupOrdinaryName);
2753  LookupQualifiedName(R, DC);
2754 
2755  if (R.isAmbiguous())
2756  return ExprError();
2757 
2759  return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2760  NameInfo, /*TemplateArgs=*/nullptr);
2761 
2762  if (R.empty()) {
2763  // Don't diagnose problems with invalid record decl, the secondary no_member
2764  // diagnostic during template instantiation is likely bogus, e.g. if a class
2765  // is invalid because it's derived from an invalid base class, then missing
2766  // members were likely supposed to be inherited.
2767  if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2768  if (CD->isInvalidDecl())
2769  return ExprError();
2770  Diag(NameInfo.getLoc(), diag::err_no_member)
2771  << NameInfo.getName() << DC << SS.getRange();
2772  return ExprError();
2773  }
2774 
2775  if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2776  // Diagnose a missing typename if this resolved unambiguously to a type in
2777  // a dependent context. If we can recover with a type, downgrade this to
2778  // a warning in Microsoft compatibility mode.
2779  unsigned DiagID = diag::err_typename_missing;
2780  if (RecoveryTSI && getLangOpts().MSVCCompat)
2781  DiagID = diag::ext_typename_missing;
2782  SourceLocation Loc = SS.getBeginLoc();
2783  auto D = Diag(Loc, DiagID);
2784  D << SS.getScopeRep() << NameInfo.getName().getAsString()
2785  << SourceRange(Loc, NameInfo.getEndLoc());
2786 
2787  // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2788  // context.
2789  if (!RecoveryTSI)
2790  return ExprError();
2791 
2792  // Only issue the fixit if we're prepared to recover.
2793  D << FixItHint::CreateInsertion(Loc, "typename ");
2794 
2795  // Recover by pretending this was an elaborated type.
2796  QualType Ty = Context.getTypeDeclType(TD);
2797  TypeLocBuilder TLB;
2798  TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2799 
2800  QualType ET = getElaboratedType(ETK_None, SS, Ty);
2801  ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2803  QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2804 
2805  *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2806 
2807  return ExprEmpty();
2808  }
2809 
2810  // Defend against this resolving to an implicit member access. We usually
2811  // won't get here if this might be a legitimate a class member (we end up in
2812  // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2813  // a pointer-to-member or in an unevaluated context in C++11.
2814  if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2815  return BuildPossibleImplicitMemberExpr(SS,
2816  /*TemplateKWLoc=*/SourceLocation(),
2817  R, /*TemplateArgs=*/nullptr, S);
2818 
2819  return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2820 }
2821 
2822 /// The parser has read a name in, and Sema has detected that we're currently
2823 /// inside an ObjC method. Perform some additional checks and determine if we
2824 /// should form a reference to an ivar.
2825 ///
2826 /// Ideally, most of this would be done by lookup, but there's
2827 /// actually quite a lot of extra work involved.
2829  IdentifierInfo *II) {
2830  SourceLocation Loc = Lookup.getNameLoc();
2831  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2832 
2833  // Check for error condition which is already reported.
2834  if (!CurMethod)
2835  return DeclResult(true);
2836 
2837  // There are two cases to handle here. 1) scoped lookup could have failed,
2838  // in which case we should look for an ivar. 2) scoped lookup could have
2839  // found a decl, but that decl is outside the current instance method (i.e.
2840  // a global variable). In these two cases, we do a lookup for an ivar with
2841  // this name, if the lookup sucedes, we replace it our current decl.
2842 
2843  // If we're in a class method, we don't normally want to look for
2844  // ivars. But if we don't find anything else, and there's an
2845  // ivar, that's an error.
2846  bool IsClassMethod = CurMethod->isClassMethod();
2847 
2848  bool LookForIvars;
2849  if (Lookup.empty())
2850  LookForIvars = true;
2851  else if (IsClassMethod)
2852  LookForIvars = false;
2853  else
2854  LookForIvars = (Lookup.isSingleResult() &&
2856  ObjCInterfaceDecl *IFace = nullptr;
2857  if (LookForIvars) {
2858  IFace = CurMethod->getClassInterface();
2859  ObjCInterfaceDecl *ClassDeclared;
2860  ObjCIvarDecl *IV = nullptr;
2861  if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2862  // Diagnose using an ivar in a class method.
2863  if (IsClassMethod) {
2864  Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2865  return DeclResult(true);
2866  }
2867 
2868  // Diagnose the use of an ivar outside of the declaring class.
2869  if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2870  !declaresSameEntity(ClassDeclared, IFace) &&
2871  !getLangOpts().DebuggerSupport)
2872  Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2873 
2874  // Success.
2875  return IV;
2876  }
2877  } else if (CurMethod->isInstanceMethod()) {
2878  // We should warn if a local variable hides an ivar.
2879  if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2880  ObjCInterfaceDecl *ClassDeclared;
2881  if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2882  if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2883  declaresSameEntity(IFace, ClassDeclared))
2884  Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2885  }
2886  }
2887  } else if (Lookup.isSingleResult() &&
2889  // If accessing a stand-alone ivar in a class method, this is an error.
2890  if (const ObjCIvarDecl *IV =
2891  dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2892  Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2893  return DeclResult(true);
2894  }
2895  }
2896 
2897  // Didn't encounter an error, didn't find an ivar.
2898  return DeclResult(false);
2899 }
2900 
2902  ObjCIvarDecl *IV) {
2903  ObjCMethodDecl *CurMethod = getCurMethodDecl();
2904  assert(CurMethod && CurMethod->isInstanceMethod() &&
2905  "should not reference ivar from this context");
2906 
2907  ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2908  assert(IFace && "should not reference ivar from this context");
2909 
2910  // If we're referencing an invalid decl, just return this as a silent
2911  // error node. The error diagnostic was already emitted on the decl.
2912  if (IV->isInvalidDecl())
2913  return ExprError();
2914 
2915  // Check if referencing a field with __attribute__((deprecated)).
2916  if (DiagnoseUseOfDecl(IV, Loc))
2917  return ExprError();
2918 
2919  // FIXME: This should use a new expr for a direct reference, don't
2920  // turn this into Self->ivar, just return a BareIVarExpr or something.
2921  IdentifierInfo &II = Context.Idents.get("self");
2922  UnqualifiedId SelfName;
2923  SelfName.setImplicitSelfParam(&II);
2924  CXXScopeSpec SelfScopeSpec;
2925  SourceLocation TemplateKWLoc;
2926  ExprResult SelfExpr =
2927  ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2928  /*HasTrailingLParen=*/false,
2929  /*IsAddressOfOperand=*/false);
2930  if (SelfExpr.isInvalid())
2931  return ExprError();
2932 
2933  SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2934  if (SelfExpr.isInvalid())
2935  return ExprError();
2936 
2937  MarkAnyDeclReferenced(Loc, IV, true);
2938 
2939  ObjCMethodFamily MF = CurMethod->getMethodFamily();
2940  if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2941  !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2942  Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2943 
2944  ObjCIvarRefExpr *Result = new (Context)
2945  ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2946  IV->getLocation(), SelfExpr.get(), true, true);
2947 
2948  if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2949  if (!isUnevaluatedContext() &&
2950  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2951  getCurFunction()->recordUseOfWeak(Result);
2952  }
2953  if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
2954  if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2955  ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2956 
2957  return Result;
2958 }
2959 
2960 /// The parser has read a name in, and Sema has detected that we're currently
2961 /// inside an ObjC method. Perform some additional checks and determine if we
2962 /// should form a reference to an ivar. If so, build an expression referencing
2963 /// that ivar.
2964 ExprResult
2966  IdentifierInfo *II, bool AllowBuiltinCreation) {
2967  // FIXME: Integrate this lookup step into LookupParsedName.
2968  DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2969  if (Ivar.isInvalid())
2970  return ExprError();
2971  if (Ivar.isUsable())
2972  return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2973  cast<ObjCIvarDecl>(Ivar.get()));
2974 
2975  if (Lookup.empty() && II && AllowBuiltinCreation)
2976  LookupBuiltin(Lookup);
2977 
2978  // Sentinel value saying that we didn't do anything special.
2979  return ExprResult(false);
2980 }
2981 
2982 /// Cast a base object to a member's actual type.
2983 ///
2984 /// There are two relevant checks:
2985 ///
2986 /// C++ [class.access.base]p7:
2987 ///
2988 /// If a class member access operator [...] is used to access a non-static
2989 /// data member or non-static member function, the reference is ill-formed if
2990 /// the left operand [...] cannot be implicitly converted to a pointer to the
2991 /// naming class of the right operand.
2992 ///
2993 /// C++ [expr.ref]p7:
2994 ///
2995 /// If E2 is a non-static data member or a non-static member function, the
2996 /// program is ill-formed if the class of which E2 is directly a member is an
2997 /// ambiguous base (11.8) of the naming class (11.9.3) of E2.
2998 ///
2999 /// Note that the latter check does not consider access; the access of the
3000 /// "real" base class is checked as appropriate when checking the access of the
3001 /// member name.
3002 ExprResult
3004  NestedNameSpecifier *Qualifier,
3005  NamedDecl *FoundDecl,
3006  NamedDecl *Member) {
3007  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3008  if (!RD)
3009  return From;
3010 
3011  QualType DestRecordType;
3012  QualType DestType;
3013  QualType FromRecordType;
3014  QualType FromType = From->getType();
3015  bool PointerConversions = false;
3016  if (isa<FieldDecl>(Member)) {
3017  DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3018  auto FromPtrType = FromType->getAs<PointerType>();
3019  DestRecordType = Context.getAddrSpaceQualType(
3020  DestRecordType, FromPtrType
3021  ? FromType->getPointeeType().getAddressSpace()
3022  : FromType.getAddressSpace());
3023 
3024  if (FromPtrType) {
3025  DestType = Context.getPointerType(DestRecordType);
3026  FromRecordType = FromPtrType->getPointeeType();
3027  PointerConversions = true;
3028  } else {
3029  DestType = DestRecordType;
3030  FromRecordType = FromType;
3031  }
3032  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
3033  if (Method->isStatic())
3034  return From;
3035 
3036  DestType = Method->getThisType();
3037  DestRecordType = DestType->getPointeeType();
3038 
3039  if (FromType->getAs<PointerType>()) {
3040  FromRecordType = FromType->getPointeeType();
3041  PointerConversions = true;
3042  } else {
3043  FromRecordType = FromType;
3044  DestType = DestRecordType;
3045  }
3046 
3047  LangAS FromAS = FromRecordType.getAddressSpace();
3048  LangAS DestAS = DestRecordType.getAddressSpace();
3049  if (FromAS != DestAS) {
3050  QualType FromRecordTypeWithoutAS =
3051  Context.removeAddrSpaceQualType(FromRecordType);
3052  QualType FromTypeWithDestAS =
3053  Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3054  if (PointerConversions)
3055  FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3056  From = ImpCastExprToType(From, FromTypeWithDestAS,
3057  CK_AddressSpaceConversion, From->getValueKind())
3058  .get();
3059  }
3060  } else {
3061  // No conversion necessary.
3062  return From;
3063  }
3064 
3065  if (DestType->isDependentType() || FromType->isDependentType())
3066  return From;
3067 
3068  // If the unqualified types are the same, no conversion is necessary.
3069  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3070  return From;
3071 
3072  SourceRange FromRange = From->getSourceRange();
3073  SourceLocation FromLoc = FromRange.getBegin();
3074 
3075  ExprValueKind VK = From->getValueKind();
3076 
3077  // C++ [class.member.lookup]p8:
3078  // [...] Ambiguities can often be resolved by qualifying a name with its
3079  // class name.
3080  //
3081  // If the member was a qualified name and the qualified referred to a
3082  // specific base subobject type, we'll cast to that intermediate type
3083  // first and then to the object in which the member is declared. That allows
3084  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3085  //
3086  // class Base { public: int x; };
3087  // class Derived1 : public Base { };
3088  // class Derived2 : public Base { };
3089  // class VeryDerived : public Derived1, public Derived2 { void f(); };
3090  //
3091  // void VeryDerived::f() {
3092  // x = 17; // error: ambiguous base subobjects
3093  // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3094  // }
3095  if (Qualifier && Qualifier->getAsType()) {
3096  QualType QType = QualType(Qualifier->getAsType(), 0);
3097  assert(QType->isRecordType() && "lookup done with non-record type");
3098 
3099  QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3100 
3101  // In C++98, the qualifier type doesn't actually have to be a base
3102  // type of the object type, in which case we just ignore it.
3103  // Otherwise build the appropriate casts.
3104  if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3105  CXXCastPath BasePath;
3106  if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3107  FromLoc, FromRange, &BasePath))
3108  return ExprError();
3109 
3110  if (PointerConversions)
3111  QType = Context.getPointerType(QType);
3112  From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3113  VK, &BasePath).get();
3114 
3115  FromType = QType;
3116  FromRecordType = QRecordType;
3117 
3118  // If the qualifier type was the same as the destination type,
3119  // we're done.
3120  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3121  return From;
3122  }
3123  }
3124 
3125  CXXCastPath BasePath;
3126  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3127  FromLoc, FromRange, &BasePath,
3128  /*IgnoreAccess=*/true))
3129  return ExprError();
3130 
3131  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3132  VK, &BasePath);
3133 }
3134 
3136  const LookupResult &R,
3137  bool HasTrailingLParen) {
3138  // Only when used directly as the postfix-expression of a call.
3139  if (!HasTrailingLParen)
3140  return false;
3141 
3142  // Never if a scope specifier was provided.
3143  if (SS.isSet())
3144  return false;
3145 
3146  // Only in C++ or ObjC++.
3147  if (!getLangOpts().CPlusPlus)
3148  return false;
3149 
3150  // Turn off ADL when we find certain kinds of declarations during
3151  // normal lookup:
3152  for (NamedDecl *D : R) {
3153  // C++0x [basic.lookup.argdep]p3:
3154  // -- a declaration of a class member
3155  // Since using decls preserve this property, we check this on the
3156  // original decl.
3157  if (D->isCXXClassMember())
3158  return false;
3159 
3160  // C++0x [basic.lookup.argdep]p3:
3161  // -- a block-scope function declaration that is not a
3162  // using-declaration
3163  // NOTE: we also trigger this for function templates (in fact, we
3164  // don't check the decl type at all, since all other decl types
3165  // turn off ADL anyway).
3166  if (isa<UsingShadowDecl>(D))
3167  D = cast<UsingShadowDecl>(D)->getTargetDecl();
3168  else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3169  return false;
3170 
3171  // C++0x [basic.lookup.argdep]p3:
3172  // -- a declaration that is neither a function or a function
3173  // template
3174  // And also for builtin functions.
3175  if (isa<FunctionDecl>(D)) {
3176  FunctionDecl *FDecl = cast<FunctionDecl>(D);
3177 
3178  // But also builtin functions.
3179  if (FDecl->getBuiltinID() && FDecl->isImplicit())
3180  return false;
3181  } else if (!isa<FunctionTemplateDecl>(D))
3182  return false;
3183  }
3184 
3185  return true;
3186 }
3187 
3188 
3189 /// Diagnoses obvious problems with the use of the given declaration
3190 /// as an expression. This is only actually called for lookups that
3191 /// were not overloaded, and it doesn't promise that the declaration
3192 /// will in fact be used.
3194  bool AcceptInvalid) {
3195  if (D->isInvalidDecl() && !AcceptInvalid)
3196  return true;
3197 
3198  if (isa<TypedefNameDecl>(D)) {
3199  S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3200  return true;
3201  }
3202 
3203  if (isa<ObjCInterfaceDecl>(D)) {
3204  S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3205  return true;
3206  }
3207 
3208  if (isa<NamespaceDecl>(D)) {
3209  S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3210  return true;
3211  }
3212 
3213  return false;
3214 }
3215 
3216 // Certain multiversion types should be treated as overloaded even when there is
3217 // only one result.
3219  assert(R.isSingleResult() && "Expected only a single result");
3220  const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3221  return FD &&
3222  (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3223 }
3224 
3226  LookupResult &R, bool NeedsADL,
3227  bool AcceptInvalidDecl) {
3228  // If this is a single, fully-resolved result and we don't need ADL,
3229  // just build an ordinary singleton decl ref.
3230  if (!NeedsADL && R.isSingleResult() &&
3234  R.getRepresentativeDecl(), nullptr,
3235  AcceptInvalidDecl);
3236 
3237  // We only need to check the declaration if there's exactly one
3238  // result, because in the overloaded case the results can only be
3239  // functions and function templates.
3241  CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3242  AcceptInvalidDecl))
3243  return ExprError();
3244 
3245  // Otherwise, just build an unresolved lookup expression. Suppress
3246  // any lookup-related diagnostics; we'll hash these out later, when
3247  // we've picked a target.
3248  R.suppressDiagnostics();
3249 
3253  R.getLookupNameInfo(),
3254  NeedsADL, R.isOverloadedResult(),
3255  R.begin(), R.end());
3256 
3257  return ULE;
3258 }
3259 
3261  SourceLocation loc,
3262  ValueDecl *var);
3263 
3264 /// Complete semantic analysis for a reference to the given declaration.
3266  const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3267  NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3268  bool AcceptInvalidDecl) {
3269  assert(D && "Cannot refer to a NULL declaration");
3270  assert(!isa<FunctionTemplateDecl>(D) &&
3271  "Cannot refer unambiguously to a function template");
3272 
3273  SourceLocation Loc = NameInfo.getLoc();
3274  if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3275  // Recovery from invalid cases (e.g. D is an invalid Decl).
3276  // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3277  // diagnostics, as invalid decls use int as a fallback type.
3278  return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3279  }
3280 
3281  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3282  // Specifically diagnose references to class templates that are missing
3283  // a template argument list.
3285  return ExprError();
3286  }
3287 
3288  // Make sure that we're referring to a value.
3289  if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3290  Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3291  Diag(D->getLocation(), diag::note_declared_at);
3292  return ExprError();
3293  }
3294 
3295  // Check whether this declaration can be used. Note that we suppress
3296  // this check when we're going to perform argument-dependent lookup
3297  // on this function name, because this might not be the function
3298  // that overload resolution actually selects.
3299  if (DiagnoseUseOfDecl(D, Loc))
3300  return ExprError();
3301 
3302  auto *VD = cast<ValueDecl>(D);
3303 
3304  // Only create DeclRefExpr's for valid Decl's.
3305  if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3306  return ExprError();
3307 
3308  // Handle members of anonymous structs and unions. If we got here,
3309  // and the reference is to a class member indirect field, then this
3310  // must be the subject of a pointer-to-member expression.
3311  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3312  if (!indirectField->isCXXClassMember())
3313  return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3314  indirectField);
3315 
3316  QualType type = VD->getType();
3317  if (type.isNull())
3318  return ExprError();
3319  ExprValueKind valueKind = VK_PRValue;
3320 
3321  // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3322  // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3323  // is expanded by some outer '...' in the context of the use.
3324  type = type.getNonPackExpansionType();
3325 
3326  switch (D->getKind()) {
3327  // Ignore all the non-ValueDecl kinds.
3328 #define ABSTRACT_DECL(kind)
3329 #define VALUE(type, base)
3330 #define DECL(type, base) case Decl::type:
3331 #include "clang/AST/DeclNodes.inc"
3332  llvm_unreachable("invalid value decl kind");
3333 
3334  // These shouldn't make it here.
3335  case Decl::ObjCAtDefsField:
3336  llvm_unreachable("forming non-member reference to ivar?");
3337 
3338  // Enum constants are always r-values and never references.
3339  // Unresolved using declarations are dependent.
3340  case Decl::EnumConstant:
3341  case Decl::UnresolvedUsingValue:
3342  case Decl::OMPDeclareReduction:
3343  case Decl::OMPDeclareMapper:
3344  valueKind = VK_PRValue;
3345  break;
3346 
3347  // Fields and indirect fields that got here must be for
3348  // pointer-to-member expressions; we just call them l-values for
3349  // internal consistency, because this subexpression doesn't really
3350  // exist in the high-level semantics.
3351  case Decl::Field:
3352  case Decl::IndirectField:
3353  case Decl::ObjCIvar:
3354  assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3355 
3356  // These can't have reference type in well-formed programs, but
3357  // for internal consistency we do this anyway.
3358  type = type.getNonReferenceType();
3359  valueKind = VK_LValue;
3360  break;
3361 
3362  // Non-type template parameters are either l-values or r-values
3363  // depending on the type.
3364  case Decl::NonTypeTemplateParm: {
3365  if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3366  type = reftype->getPointeeType();
3367  valueKind = VK_LValue; // even if the parameter is an r-value reference
3368  break;
3369  }
3370 
3371  // [expr.prim.id.unqual]p2:
3372  // If the entity is a template parameter object for a template
3373  // parameter of type T, the type of the expression is const T.
3374  // [...] The expression is an lvalue if the entity is a [...] template
3375  // parameter object.
3376  if (type->isRecordType()) {
3377  type = type.getUnqualifiedType().withConst();
3378  valueKind = VK_LValue;
3379  break;
3380  }
3381 
3382  // For non-references, we need to strip qualifiers just in case
3383  // the template parameter was declared as 'const int' or whatever.
3384  valueKind = VK_PRValue;
3385  type = type.getUnqualifiedType();
3386  break;
3387  }
3388 
3389  case Decl::Var:
3390  case Decl::VarTemplateSpecialization:
3391  case Decl::VarTemplatePartialSpecialization:
3392  case Decl::Decomposition:
3393  case Decl::OMPCapturedExpr:
3394  // In C, "extern void blah;" is valid and is an r-value.
3395  if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3396  type->isVoidType()) {
3397  valueKind = VK_PRValue;
3398  break;
3399  }
3400  [[fallthrough]];
3401 
3402  case Decl::ImplicitParam:
3403  case Decl::ParmVar: {
3404  // These are always l-values.
3405  valueKind = VK_LValue;
3406  type = type.getNonReferenceType();
3407 
3408  // FIXME: Does the addition of const really only apply in
3409  // potentially-evaluated contexts? Since the variable isn't actually
3410  // captured in an unevaluated context, it seems that the answer is no.
3411  if (!isUnevaluatedContext()) {
3412  QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3413  if (!CapturedType.isNull())
3414  type = CapturedType;
3415  }
3416 
3417  break;
3418  }
3419 
3420  case Decl::Binding:
3421  // These are always lvalues.
3422  valueKind = VK_LValue;
3423  type = type.getNonReferenceType();
3424  break;
3425 
3426  case Decl::Function: {
3427  if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3430  valueKind = VK_PRValue;
3431  break;
3432  }
3433  }
3434 
3435  const FunctionType *fty = type->castAs<FunctionType>();
3436 
3437  // If we're referring to a function with an __unknown_anytype
3438  // result type, make the entire expression __unknown_anytype.
3439  if (fty->getReturnType() == Context.UnknownAnyTy) {
3441  valueKind = VK_PRValue;
3442  break;
3443  }
3444 
3445  // Functions are l-values in C++.
3446  if (getLangOpts().CPlusPlus) {
3447  valueKind = VK_LValue;
3448  break;
3449  }
3450 
3451  // C99 DR 316 says that, if a function type comes from a
3452  // function definition (without a prototype), that type is only
3453  // used for checking compatibility. Therefore, when referencing
3454  // the function, we pretend that we don't have the full function
3455  // type.
3456  if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3458  fty->getExtInfo());
3459 
3460  // Functions are r-values in C.
3461  valueKind = VK_PRValue;
3462  break;
3463  }
3464 
3465  case Decl::CXXDeductionGuide:
3466  llvm_unreachable("building reference to deduction guide");
3467 
3468  case Decl::MSProperty:
3469  case Decl::MSGuid:
3470  case Decl::TemplateParamObject:
3471  // FIXME: Should MSGuidDecl and template parameter objects be subject to
3472  // capture in OpenMP, or duplicated between host and device?
3473  valueKind = VK_LValue;
3474  break;
3475 
3476  case Decl::UnnamedGlobalConstant:
3477  valueKind = VK_LValue;
3478  break;
3479 
3480  case Decl::CXXMethod:
3481  // If we're referring to a method with an __unknown_anytype
3482  // result type, make the entire expression __unknown_anytype.
3483  // This should only be possible with a type written directly.
3484  if (const FunctionProtoType *proto =
3485  dyn_cast<FunctionProtoType>(VD->getType()))
3486  if (proto->getReturnType() == Context.UnknownAnyTy) {
3488  valueKind = VK_PRValue;
3489  break;
3490  }
3491 
3492  // C++ methods are l-values if static, r-values if non-static.
3493  if (cast<CXXMethodDecl>(VD)->isStatic()) {
3494  valueKind = VK_LValue;
3495  break;
3496  }
3497  [[fallthrough]];
3498 
3499  case Decl::CXXConversion:
3500  case Decl::CXXDestructor:
3501  case Decl::CXXConstructor:
3502  valueKind = VK_PRValue;
3503  break;
3504  }
3505 
3506  auto *E =
3507  BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3508  /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3509  // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3510  // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3511  // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3512  // diagnostics).
3513  if (VD->isInvalidDecl() && E)
3514  return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3515  return E;
3516 }
3517 
3518 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3519  SmallString<32> &Target) {
3520  Target.resize(CharByteWidth * (Source.size() + 1));
3521  char *ResultPtr = &Target[0];
3522  const llvm::UTF8 *ErrorPtr;
3523  bool success =
3524  llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3525  (void)success;
3526  assert(success);
3527  Target.resize(ResultPtr - &Target[0]);
3528 }
3529 
3532  // Pick the current block, lambda, captured statement or function.
3533  Decl *currentDecl = nullptr;
3534  if (const BlockScopeInfo *BSI = getCurBlock())
3535  currentDecl = BSI->TheDecl;
3536  else if (const LambdaScopeInfo *LSI = getCurLambda())
3537  currentDecl = LSI->CallOperator;
3538  else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3539  currentDecl = CSI->TheCapturedDecl;
3540  else
3541  currentDecl = getCurFunctionOrMethodDecl();
3542 
3543  if (!currentDecl) {
3544  Diag(Loc, diag::ext_predef_outside_function);
3545  currentDecl = Context.getTranslationUnitDecl();
3546  }
3547 
3548  QualType ResTy;
3549  StringLiteral *SL = nullptr;
3550  if (cast<DeclContext>(currentDecl)->isDependentContext())
3551  ResTy = Context.DependentTy;
3552  else {
3553  // Pre-defined identifiers are of type char[x], where x is the length of
3554  // the string.
3555  auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3556  unsigned Length = Str.length();
3557 
3558  llvm::APInt LengthI(32, Length + 1);
3560  ResTy =
3562  SmallString<32> RawChars;
3564  Str, RawChars);
3565  ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3567  /*IndexTypeQuals*/ 0);
3569  /*Pascal*/ false, ResTy, Loc);
3570  } else {
3572  ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3574  /*IndexTypeQuals*/ 0);
3576  /*Pascal*/ false, ResTy, Loc);
3577  }
3578  }
3579 
3580  return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3581 }
3582 
3584  SourceLocation LParen,
3585  SourceLocation RParen,
3586  TypeSourceInfo *TSI) {
3587  return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3588 }
3589 
3591  SourceLocation LParen,
3592  SourceLocation RParen,
3593  ParsedType ParsedTy) {
3594  TypeSourceInfo *TSI = nullptr;
3595  QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3596 
3597  if (Ty.isNull())
3598  return ExprError();
3599  if (!TSI)
3600  TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3601 
3602  return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3603 }
3604 
3607 
3608  switch (Kind) {
3609  default: llvm_unreachable("Unknown simple primary expr!");
3610  case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3611  case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3612  case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3613  case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3614  case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3615  case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3616  case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3617  }
3618 
3619  return BuildPredefinedExpr(Loc, IK);
3620 }
3621 
3623  SmallString<16> CharBuffer;
3624  bool Invalid = false;
3625  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3626  if (Invalid)
3627  return ExprError();
3628 
3629  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3630  PP, Tok.getKind());
3631  if (Literal.hadError())
3632  return ExprError();
3633 
3634  QualType Ty;
3635  if (Literal.isWide())
3636  Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3637  else if (Literal.isUTF8() && getLangOpts().C2x)
3638  Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3639  else if (Literal.isUTF8() && getLangOpts().Char8)
3640  Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3641  else if (Literal.isUTF16())
3642  Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3643  else if (Literal.isUTF32())
3644  Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3645  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3646  Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3647  else
3648  Ty = Context.CharTy; // 'x' -> char in C++;
3649  // u8'x' -> char in C11-C17 and in C++ without char8_t.
3650 
3652  if (Literal.isWide())
3654  else if (Literal.isUTF16())
3656  else if (Literal.isUTF32())
3658  else if (Literal.isUTF8())
3660 
3661  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3662  Tok.getLocation());
3663 
3664  if (Literal.getUDSuffix().empty())
3665  return Lit;
3666 
3667  // We're building a user-defined literal.
3668  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3669  SourceLocation UDSuffixLoc =
3670  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3671 
3672  // Make sure we're allowed user-defined literals here.
3673  if (!UDLScope)
3674  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3675 
3676  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3677  // operator "" X (ch)
3678  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3679  Lit, Tok.getLocation());
3680 }
3681 
3683  unsigned IntSize = Context.getTargetInfo().getIntWidth();
3684  return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3685  Context.IntTy, Loc);
3686 }
3687 
3689  QualType Ty, SourceLocation Loc) {
3690  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3691 
3692  using llvm::APFloat;
3693  APFloat Val(Format);
3694 
3695  APFloat::opStatus result = Literal.GetFloatValue(Val);
3696 
3697  // Overflow is always an error, but underflow is only an error if
3698  // we underflowed to zero (APFloat reports denormals as underflow).
3699  if ((result & APFloat::opOverflow) ||
3700  ((result & APFloat::opUnderflow) && Val.isZero())) {
3701  unsigned diagnostic;
3702  SmallString<20> buffer;
3703  if (result & APFloat::opOverflow) {
3704  diagnostic = diag::warn_float_overflow;
3705  APFloat::getLargest(Format).toString(buffer);
3706  } else {
3707  diagnostic = diag::warn_float_underflow;
3708  APFloat::getSmallest(Format).toString(buffer);
3709  }
3710 
3711  S.Diag(Loc, diagnostic)
3712  << Ty
3713  << StringRef(buffer.data(), buffer.size());
3714  }
3715 
3716  bool isExact = (result == APFloat::opOK);
3717  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3718 }
3719 
3721  assert(E && "Invalid expression");
3722 
3723  if (E->isValueDependent())
3724  return false;
3725 
3726  QualType QT = E->getType();
3727  if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3728  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3729  return true;
3730  }
3731 
3732  llvm::APSInt ValueAPS;
3733  ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3734 
3735  if (R.isInvalid())
3736  return true;
3737 
3738  bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3739  if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3740  Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3741  << toString(ValueAPS, 10) << ValueIsPositive;
3742  return true;
3743  }
3744 
3745  return false;
3746 }
3747 
3749  // Fast path for a single digit (which is quite common). A single digit
3750  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3751  if (Tok.getLength() == 1) {
3752  const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3753  return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3754  }
3755 
3756  SmallString<128> SpellingBuffer;
3757  // NumericLiteralParser wants to overread by one character. Add padding to
3758  // the buffer in case the token is copied to the buffer. If getSpelling()
3759  // returns a StringRef to the memory buffer, it should have a null char at
3760  // the EOF, so it is also safe.
3761  SpellingBuffer.resize(Tok.getLength() + 1);
3762 
3763  // Get the spelling of the token, which eliminates trigraphs, etc.
3764  bool Invalid = false;
3765  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3766  if (Invalid)
3767  return ExprError();
3768 
3769  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3772  if (Literal.hadError)
3773  return ExprError();
3774 
3775  if (Literal.hasUDSuffix()) {
3776  // We're building a user-defined literal.
3777  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3778  SourceLocation UDSuffixLoc =
3779  getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3780 
3781  // Make sure we're allowed user-defined literals here.
3782  if (!UDLScope)
3783  return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3784 
3785  QualType CookedTy;
3786  if (Literal.isFloatingLiteral()) {
3787  // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3788  // long double, the literal is treated as a call of the form
3789  // operator "" X (f L)
3790  CookedTy = Context.LongDoubleTy;
3791  } else {
3792  // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3793  // unsigned long long, the literal is treated as a call of the form
3794  // operator "" X (n ULL)
3795  CookedTy = Context.UnsignedLongLongTy;
3796  }
3797 
3798  DeclarationName OpName =
3800  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3801  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3802 
3803  SourceLocation TokLoc = Tok.getLocation();
3804 
3805  // Perform literal operator lookup to determine if we're building a raw
3806  // literal or a cooked one.
3807  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3808  switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3809  /*AllowRaw*/ true, /*AllowTemplate*/ true,
3810  /*AllowStringTemplatePack*/ false,
3811  /*DiagnoseMissing*/ !Literal.isImaginary)) {
3813  // Lookup failure for imaginary constants isn't fatal, there's still the
3814  // GNU extension producing _Complex types.
3815  break;
3816  case LOLR_Error:
3817  return ExprError();
3818  case LOLR_Cooked: {
3819  Expr *Lit;
3820  if (Literal.isFloatingLiteral()) {
3821  Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3822  } else {
3824  if (Literal.GetIntegerValue(ResultVal))
3825  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3826  << /* Unsigned */ 1;
3827  Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3828  Tok.getLocation());
3829  }
3830  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3831  }
3832 
3833  case LOLR_Raw: {
3834  // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3835  // literal is treated as a call of the form
3836  // operator "" X ("n")
3837  unsigned Length = Literal.getUDSuffixOffset();
3840  llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3841  Expr *Lit =
3842  StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3844  /*Pascal*/ false, StrTy, &TokLoc, 1);
3845  return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3846  }
3847 
3848  case LOLR_Template: {
3849  // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3850  // template), L is treated as a call fo the form
3851  // operator "" X <'c1', 'c2', ... 'ck'>()
3852  // where n is the source character sequence c1 c2 ... ck.
3853  TemplateArgumentListInfo ExplicitArgs;
3854  unsigned CharBits = Context.getIntWidth(Context.CharTy);
3855  bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3856  llvm::APSInt Value(CharBits, CharIsUnsigned);
3857  for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3858  Value = TokSpelling[I];
3860  TemplateArgumentLocInfo ArgInfo;
3861  ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3862  }
3863  return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
3864  &ExplicitArgs);
3865  }
3867  llvm_unreachable("unexpected literal operator lookup result");
3868  }
3869  }
3870 
3871  Expr *Res;
3872 
3873  if (Literal.isFixedPointLiteral()) {
3874  QualType Ty;
3875 
3876  if (Literal.isAccum) {
3877  if (Literal.isHalf) {
3878  Ty = Context.ShortAccumTy;
3879  } else if (Literal.isLong) {
3880  Ty = Context.LongAccumTy;
3881  } else {
3882  Ty = Context.AccumTy;
3883  }
3884  } else if (Literal.isFract) {
3885  if (Literal.isHalf) {
3886  Ty = Context.ShortFractTy;
3887  } else if (Literal.isLong) {
3888  Ty = Context.LongFractTy;
3889  } else {
3890  Ty = Context.FractTy;
3891  }
3892  }
3893 
3894  if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3895 
3896  bool isSigned = !Literal.isUnsigned;
3897  unsigned scale = Context.getFixedPointScale(Ty);
3898  unsigned bit_width = Context.getTypeInfo(Ty).Width;
3899 
3900  llvm::APInt Val(bit_width, 0, isSigned);
3901  bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3902  bool ValIsZero = Val.isZero() && !Overflowed;
3903 
3904  auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3905  if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3906  // Clause 6.4.4 - The value of a constant shall be in the range of
3907  // representable values for its type, with exception for constants of a
3908  // fract type with a value of exactly 1; such a constant shall denote
3909  // the maximal value for the type.
3910  --Val;
3911  else if (Val.ugt(MaxVal) || Overflowed)
3912  Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3913 
3915  Tok.getLocation(), scale);
3916  } else if (Literal.isFloatingLiteral()) {
3917  QualType Ty;
3918  if (Literal.isHalf){
3919  if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3920  Ty = Context.HalfTy;
3921  else {
3922  Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3923  return ExprError();
3924  }
3925  } else if (Literal.isFloat)
3926  Ty = Context.FloatTy;
3927  else if (Literal.isLong)
3928  Ty = Context.LongDoubleTy;
3929  else if (Literal.isFloat16)
3930  Ty = Context.Float16Ty;
3931  else if (Literal.isFloat128)
3932  Ty = Context.Float128Ty;
3933  else
3934  Ty = Context.DoubleTy;
3935 
3936  Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3937 
3938  if (Ty == Context.DoubleTy) {
3939  if (getLangOpts().SinglePrecisionConstants) {
3940  if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3941  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3942  }
3943  } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3944  "cl_khr_fp64", getLangOpts())) {
3945  // Impose single-precision float type when cl_khr_fp64 is not enabled.
3946  Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3947  << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3948  Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3949  }
3950  }
3951  } else if (!Literal.isIntegerLiteral()) {
3952  return ExprError();
3953  } else {
3954  QualType Ty;
3955 
3956  // 'z/uz' literals are a C++2b feature.
3957  if (Literal.isSizeT)
3960  ? diag::warn_cxx20_compat_size_t_suffix
3961  : diag::ext_cxx2b_size_t_suffix
3962  : diag::err_cxx2b_size_t_suffix);
3963 
3964  // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3965  // but we do not currently support the suffix in C++ mode because it's not
3966  // entirely clear whether WG21 will prefer this suffix to return a library
3967  // type such as std::bit_int instead of returning a _BitInt.
3968  if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3969  PP.Diag(Tok.getLocation(), getLangOpts().C2x
3970  ? diag::warn_c2x_compat_bitint_suffix
3971  : diag::ext_c2x_bitint_suffix);
3972 
3973  // Get the value in the widest-possible width. What is "widest" depends on
3974  // whether the literal is a bit-precise integer or not. For a bit-precise
3975  // integer type, try to scan the source to determine how many bits are
3976  // needed to represent the value. This may seem a bit expensive, but trying
3977  // to get the integer value from an overly-wide APInt is *extremely*
3978  // expensive, so the naive approach of assuming
3979  // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3980  unsigned BitsNeeded =
3981  Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3982  Literal.getLiteralDigits(), Literal.getRadix())
3984  llvm::APInt ResultVal(BitsNeeded, 0);
3985 
3986  if (Literal.GetIntegerValue(ResultVal)) {
3987  // If this value didn't fit into uintmax_t, error and force to ull.
3988  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3989  << /* Unsigned */ 1;
3991  assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3992  "long long is not intmax_t?");
3993  } else {
3994  // If this value fits into a ULL, try to figure out what else it fits into
3995  // according to the rules of C99 6.4.4.1p5.
3996 
3997  // Octal, Hexadecimal, and integers with a U suffix are allowed to
3998  // be an unsigned int.
3999  bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4000 
4001  // Check from smallest to largest, picking the smallest type we can.
4002  unsigned Width = 0;
4003 
4004  // Microsoft specific integer suffixes are explicitly sized.
4005  if (Literal.MicrosoftInteger) {
4006  if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4007  Width = 8;
4008  Ty = Context.CharTy;
4009  } else {
4010  Width = Literal.MicrosoftInteger;
4011  Ty = Context.getIntTypeForBitwidth(Width,
4012  /*Signed=*/!Literal.isUnsigned);
4013  }
4014  }
4015 
4016  // Bit-precise integer literals are automagically-sized based on the
4017  // width required by the literal.
4018  if (Literal.isBitInt) {
4019  // The signed version has one more bit for the sign value. There are no
4020  // zero-width bit-precise integers, even if the literal value is 0.
4021  Width = std::max(ResultVal.getActiveBits(), 1u) +
4022  (Literal.isUnsigned ? 0u : 1u);
4023 
4024  // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4025  // and reset the type to the largest supported width.
4026  unsigned int MaxBitIntWidth =
4028  if (Width > MaxBitIntWidth) {
4029  Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4030  << Literal.isUnsigned;
4031  Width = MaxBitIntWidth;
4032  }
4033 
4034  // Reset the result value to the smaller APInt and select the correct
4035  // type to be used. Note, we zext even for signed values because the
4036  // literal itself is always an unsigned value (a preceeding - is a
4037  // unary operator, not part of the literal).
4038  ResultVal = ResultVal.zextOrTrunc(Width);
4039  Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4040  }
4041 
4042  // Check C++2b size_t literals.
4043  if (Literal.isSizeT) {
4044  assert(!Literal.MicrosoftInteger &&
4045  "size_t literals can't be Microsoft literals");
4046  unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4048 
4049  // Does it fit in size_t?
4050  if (ResultVal.isIntN(SizeTSize)) {
4051  // Does it fit in ssize_t?
4052  if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4053  Ty = Context.getSignedSizeType();
4054  else if (AllowUnsigned)
4055  Ty = Context.getSizeType();
4056  Width = SizeTSize;
4057  }
4058  }
4059 
4060  if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4061  !Literal.isSizeT) {
4062  // Are int/unsigned possibilities?
4063  unsigned IntSize = Context.getTargetInfo().getIntWidth();
4064 
4065  // Does it fit in a unsigned int?
4066  if (ResultVal.isIntN(IntSize)) {
4067  // Does it fit in a signed int?
4068  if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4069  Ty = Context.IntTy;
4070  else if (AllowUnsigned)
4071  Ty = Context.UnsignedIntTy;
4072  Width = IntSize;
4073  }
4074  }
4075 
4076  // Are long/unsigned long possibilities?
4077  if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4078  unsigned LongSize = Context.getTargetInfo().getLongWidth();
4079 
4080  // Does it fit in a unsigned long?
4081  if (ResultVal.isIntN(LongSize)) {
4082  // Does it fit in a signed long?
4083  if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4084  Ty = Context.LongTy;
4085  else if (AllowUnsigned)
4086  Ty = Context.UnsignedLongTy;
4087  // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4088  // is compatible.
4089  else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4090  const unsigned LongLongSize =
4092  Diag(Tok.getLocation(),
4094  ? Literal.isLong
4095  ? diag::warn_old_implicitly_unsigned_long_cxx
4096  : /*C++98 UB*/ diag::
4097  ext_old_implicitly_unsigned_long_cxx
4098  : diag::warn_old_implicitly_unsigned_long)
4099  << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4100  : /*will be ill-formed*/ 1);
4101  Ty = Context.UnsignedLongTy;
4102  }
4103  Width = LongSize;
4104  }
4105  }
4106 
4107  // Check long long if needed.
4108  if (Ty.isNull() && !Literal.isSizeT) {
4109  unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4110 
4111  // Does it fit in a unsigned long long?
4112  if (ResultVal.isIntN(LongLongSize)) {
4113  // Does it fit in a signed long long?
4114  // To be compatible with MSVC, hex integer literals ending with the
4115  // LL or i64 suffix are always signed in Microsoft mode.
4116  if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4117  (getLangOpts().MSVCCompat && Literal.isLongLong)))
4118  Ty = Context.LongLongTy;
4119  else if (AllowUnsigned)
4121  Width = LongLongSize;
4122 
4123  // 'long long' is a C99 or C++11 feature, whether the literal
4124  // explicitly specified 'long long' or we needed the extra width.
4125  if (getLangOpts().CPlusPlus)
4126  Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4127  ? diag::warn_cxx98_compat_longlong
4128  : diag::ext_cxx11_longlong);
4129  else if (!getLangOpts().C99)
4130  Diag(Tok.getLocation(), diag::ext_c99_longlong);
4131  }
4132  }
4133 
4134  // If we still couldn't decide a type, we either have 'size_t' literal
4135  // that is out of range, or a decimal literal that does not fit in a
4136  // signed long long and has no U suffix.
4137  if (Ty.isNull()) {
4138  if (Literal.isSizeT)
4139  Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4140  << Literal.isUnsigned;
4141  else
4142  Diag(Tok.getLocation(),
4143  diag::ext_integer_literal_too_large_for_signed);
4146  }
4147 
4148  if (ResultVal.getBitWidth() != Width)
4149  ResultVal = ResultVal.trunc(Width);
4150  }
4151  Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4152  }
4153 
4154  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4155  if (Literal.isImaginary) {
4156  Res = new (Context) ImaginaryLiteral(Res,
4157  Context.getComplexType(Res->getType()));
4158 
4159  Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4160  }
4161  return Res;
4162 }
4163 
4165  assert(E && "ActOnParenExpr() missing expr");
4166  QualType ExprTy = E->getType();
4167  if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4168  !E->isLValue() && ExprTy->hasFloatingRepresentation())
4169  return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4170  return new (Context) ParenExpr(L, R, E);
4171 }
4172 
4174  SourceLocation Loc,
4175  SourceRange ArgRange) {
4176  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4177  // scalar or vector data type argument..."
4178  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4179  // type (C99 6.2.5p18) or void.
4180  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4181  S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4182  << T << ArgRange;
4183  return true;
4184  }
4185 
4186  assert((T->isVoidType() || !T->isIncompleteType()) &&
4187  "Scalar types should always be complete");
4188  return false;
4189 }
4190 
4192  SourceLocation Loc,
4193  SourceRange ArgRange,
4194  UnaryExprOrTypeTrait TraitKind) {
4195  // Invalid types must be hard errors for SFINAE in C++.
4196  if (S.LangOpts.CPlusPlus)
4197  return true;
4198 
4199  // C99 6.5.3.4p1:
4200  if (T->isFunctionType() &&
4201  (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4202  TraitKind == UETT_PreferredAlignOf)) {
4203  // sizeof(function)/alignof(function) is allowed as an extension.
4204  S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4205  << getTraitSpelling(TraitKind) << ArgRange;
4206  return false;
4207  }
4208 
4209  // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4210  // this is an error (OpenCL v1.1 s6.3.k)
4211  if (T->isVoidType()) {
4212  unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4213  : diag::ext_sizeof_alignof_void_type;
4214  S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4215  return false;
4216  }
4217 
4218  return true;
4219 }
4220 
4222  SourceLocation Loc,
4223  SourceRange ArgRange,
4224  UnaryExprOrTypeTrait TraitKind) {
4225  // Reject sizeof(interface) and sizeof(interface<proto>) if the
4226  // runtime doesn't allow it.
4228  S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4229  << T << (TraitKind == UETT_SizeOf)
4230  << ArgRange;
4231  return true;
4232  }
4233 
4234  return false;
4235 }
4236 
4237 /// Check whether E is a pointer from a decayed array type (the decayed
4238 /// pointer type is equal to T) and emit a warning if it is.
4240  Expr *E) {
4241  // Don't warn if the operation changed the type.
4242  if (T != E->getType())
4243  return;
4244 
4245  // Now look for array decays.
4246  ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4247  if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4248  return;
4249 
4250  S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4251  << ICE->getType()
4252  << ICE->getSubExpr()->getType();
4253 }
4254 
4255 /// Check the constraints on expression operands to unary type expression
4256 /// and type traits.
4257 ///
4258 /// Completes any types necessary and validates the constraints on the operand
4259 /// expression. The logic mostly mirrors the type-based overload, but may modify
4260 /// the expression as it completes the type for that expression through template
4261 /// instantiation, etc.
4263  UnaryExprOrTypeTrait ExprKind) {
4264  QualType ExprTy = E->getType();
4265  assert(!ExprTy->isReferenceType());
4266 
4267  bool IsUnevaluatedOperand =
4268  (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4269  ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4270  if (IsUnevaluatedOperand) {
4271  ExprResult Result = CheckUnevaluatedOperand(E);
4272  if (Result.isInvalid())
4273  return true;
4274  E = Result.get();
4275  }
4276 
4277  // The operand for sizeof and alignof is in an unevaluated expression context,
4278  // so side effects could result in unintended consequences.
4279  // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4280  // used to build SFINAE gadgets.
4281  // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4282  if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4283  !E->isInstantiationDependent() &&
4284  !E->getType()->isVariableArrayType() &&
4285  E->HasSideEffects(Context, false))
4286  Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4287 
4288  if (ExprKind == UETT_VecStep)
4289  return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4290  E->getSourceRange());
4291 
4292  // Explicitly list some types as extensions.
4293  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4294  E->getSourceRange(), ExprKind))
4295  return false;
4296 
4297  // 'alignof' applied to an expression only requires the base element type of
4298  // the expression to be complete. 'sizeof' requires the expression's type to
4299  // be complete (and will attempt to complete it if it's an array of unknown
4300  // bound).
4301  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4304  diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4305  getTraitSpelling(ExprKind), E->getSourceRange()))
4306  return true;
4307  } else {
4309  E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4310  getTraitSpelling(ExprKind), E->getSourceRange()))
4311  return true;
4312  }
4313 
4314  // Completing the expression's type may have changed it.
4315  ExprTy = E->getType();
4316  assert(!ExprTy->isReferenceType());
4317 
4318  if (ExprTy->isFunctionType()) {
4319  Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4320  << getTraitSpelling(ExprKind) << E->getSourceRange();
4321  return true;
4322  }
4323 
4324  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4325  E->getSourceRange(), ExprKind))
4326  return true;
4327 
4328  if (ExprKind == UETT_SizeOf) {
4329  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4330  if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4331  QualType OType = PVD->getOriginalType();
4332  QualType Type = PVD->getType();
4333  if (Type->isPointerType() && OType->isArrayType()) {
4334  Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4335  << Type << OType;
4336  Diag(PVD->getLocation(), diag::note_declared_at);
4337  }
4338  }
4339  }
4340 
4341  // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4342  // decays into a pointer and returns an unintended result. This is most
4343  // likely a typo for "sizeof(array) op x".
4344  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4345  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4346  BO->getLHS());
4347  warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4348  BO->getRHS());
4349  }
4350  }
4351 
4352  return false;
4353 }
4354 
4355 /// Check the constraints on operands to unary expression and type
4356 /// traits.
4357 ///
4358 /// This will complete any types necessary, and validate the various constraints
4359 /// on those operands.
4360 ///
4361 /// The UsualUnaryConversions() function is *not* called by this routine.
4362 /// C99 6.3.2.1p[2-4] all state:
4363 /// Except when it is the operand of the sizeof operator ...
4364 ///
4365 /// C++ [expr.sizeof]p4
4366 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4367 /// standard conversions are not applied to the operand of sizeof.
4368 ///
4369 /// This policy is followed for all of the unary trait expressions.
4371  SourceLocation OpLoc,
4372  SourceRange ExprRange,
4373  UnaryExprOrTypeTrait ExprKind) {
4374  if (ExprType->isDependentType())
4375  return false;
4376 
4377  // C++ [expr.sizeof]p2:
4378  // When applied to a reference or a reference type, the result
4379  // is the size of the referenced type.
4380  // C++11 [expr.alignof]p3:
4381  // When alignof is applied to a reference type, the result
4382  // shall be the alignment of the referenced type.
4383  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4384  ExprType = Ref->getPointeeType();
4385 
4386  // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4387  // When alignof or _Alignof is applied to an array type, the result
4388  // is the alignment of the element type.
4389  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4390  ExprKind == UETT_OpenMPRequiredSimdAlign)
4391  ExprType = Context.getBaseElementType(ExprType);
4392 
4393  if (ExprKind == UETT_VecStep)
4394  return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4395 
4396  // Explicitly list some types as extensions.
4397  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4398  ExprKind))
4399  return false;
4400 
4402  OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4403  getTraitSpelling(ExprKind), ExprRange))
4404  return true;
4405 
4406  if (ExprType->isFunctionType()) {
4407  Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4408  << getTraitSpelling(ExprKind) << ExprRange;
4409  return true;
4410  }
4411 
4412  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4413  ExprKind))
4414  return true;
4415 
4416  return false;
4417 }
4418 
4419 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4420  // Cannot know anything else if the expression is dependent.
4421  if (E->isTypeDependent())
4422  return false;
4423 
4424  if (E->getObjectKind() == OK_BitField) {
4425  S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4426  << 1 << E->getSourceRange();
4427  return true;
4428  }
4429 
4430  ValueDecl *D = nullptr;
4431  Expr *Inner = E->IgnoreParens();
4432  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4433  D = DRE->getDecl();
4434  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4435  D = ME->getMemberDecl();
4436  }
4437 
4438  // If it's a field, require the containing struct to have a
4439  // complete definition so that we can compute the layout.
4440  //
4441  // This can happen in C++11 onwards, either by naming the member
4442  // in a way that is not transformed into a member access expression
4443  // (in an unevaluated operand, for instance), or by naming the member
4444  // in a trailing-return-type.
4445  //
4446  // For the record, since __alignof__ on expressions is a GCC
4447  // extension, GCC seems to permit this but always gives the
4448  // nonsensical answer 0.
4449  //
4450  // We don't really need the layout here --- we could instead just
4451  // directly check for all the appropriate alignment-lowing
4452  // attributes --- but that would require duplicating a lot of
4453  // logic that just isn't worth duplicating for such a marginal
4454  // use-case.
4455  if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4456  // Fast path this check, since we at least know the record has a
4457  // definition if we can find a member of it.
4458  if (!FD->getParent()->isCompleteDefinition()) {
4459  S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4460  << E->getSourceRange();
4461  return true;
4462  }
4463 
4464  // Otherwise, if it's a field, and the field doesn't have
4465  // reference type, then it must have a complete type (or be a
4466  // flexible array member, which we explicitly want to
4467  // white-list anyway), which makes the following checks trivial.
4468  if (!FD->getType()->isReferenceType())
4469  return false;
4470  }
4471 
4472  return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4473 }
4474 
4476  E = E->IgnoreParens();
4477 
4478  // Cannot know anything else if the expression is dependent.
4479  if (E->isTypeDependent())
4480  return false;
4481 
4482  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4483 }
4484 
4486  CapturingScopeInfo *CSI) {
4487  assert(T->isVariablyModifiedType());
4488  assert(CSI != nullptr);
4489 
4490  // We're going to walk down into the type and look for VLA expressions.
4491  do {
4492  const Type *Ty = T.getTypePtr();
4493  switch (Ty->getTypeClass()) {
4494 #define TYPE(Class, Base)
4495 #define ABSTRACT_TYPE(Class, Base)
4496 #define NON_CANONICAL_TYPE(Class, Base)
4497 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4498 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4499 #include "clang/AST/TypeNodes.inc"
4500  T = QualType();
4501  break;
4502  // These types are never variably-modified.
4503  case Type::Builtin:
4504  case Type::Complex:
4505  case Type::Vector:
4506  case Type::ExtVector:
4507  case Type::ConstantMatrix:
4508  case Type::Record:
4509  case Type::Enum:
4510  case Type::TemplateSpecialization:
4511  case Type::ObjCObject:
4512  case Type::ObjCInterface:
4513  case Type::ObjCObjectPointer:
4514  case Type::ObjCTypeParam:
4515  case Type::Pipe:
4516  case Type::BitInt:
4517  llvm_unreachable("type class is never variably-modified!");
4518  case Type::Elaborated:
4519  T = cast<ElaboratedType>(Ty)->getNamedType();
4520  break;
4521  case Type::Adjusted:
4522  T = cast<AdjustedType>(Ty)->getOriginalType();
4523  break;
4524  case Type::Decayed:
4525  T = cast<DecayedType>(Ty)->getPointeeType();
4526  break;
4527  case Type::Pointer:
4528  T = cast<PointerType>(Ty)->getPointeeType();
4529  break;
4530  case Type::BlockPointer:
4531  T = cast<BlockPointerType>(Ty)->getPointeeType();
4532  break;
4533  case Type::LValueReference:
4534  case Type::RValueReference:
4535  T = cast<ReferenceType>(Ty)->getPointeeType();
4536  break;
4537  case Type::MemberPointer:
4538  T = cast<MemberPointerType>(Ty)->getPointeeType();
4539  break;
4540  case Type::ConstantArray:
4541  case Type::IncompleteArray:
4542  // Losing element qualification here is fine.
4543  T = cast<ArrayType>(Ty)->getElementType();
4544  break;
4545  case Type::VariableArray: {
4546  // Losing element qualification here is fine.
4547  const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4548 
4549  // Unknown size indication requires no size computation.
4550  // Otherwise, evaluate and record it.
4551  auto Size = VAT->getSizeExpr();
4552  if (Size && !CSI->isVLATypeCaptured(VAT) &&
4553  (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4554  CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4555 
4556  T = VAT->getElementType();
4557  break;
4558  }
4559  case Type::FunctionProto:
4560  case Type::FunctionNoProto:
4561  T = cast<FunctionType>(Ty)->getReturnType();
4562  break;
4563  case Type::Paren:
4564  case Type::TypeOf:
4565  case Type::UnaryTransform:
4566  case Type::Attributed:
4567  case Type::BTFTagAttributed:
4568  case Type::SubstTemplateTypeParm:
4569  case Type::MacroQualified:
4570  // Keep walking after single level desugaring.
4571  T = T.getSingleStepDesugaredType(Context);
4572  break;
4573  case Type::Typedef:
4574  T = cast<TypedefType>(Ty)->desugar();
4575  break;
4576  case Type::Decltype:
4577  T = cast<DecltypeType>(Ty)->desugar();
4578  break;
4579  case Type::Using:
4580  T = cast<UsingType>(Ty)->desugar();
4581  break;
4582  case Type::Auto:
4583  case Type::DeducedTemplateSpecialization:
4584  T = cast<DeducedType>(Ty)->getDeducedType();
4585  break;
4586  case Type::TypeOfExpr:
4587  T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4588  break;
4589  case Type::Atomic:
4590  T = cast<AtomicType>(Ty)->getValueType();
4591  break;
4592  }
4593  } while (!T.isNull() && T->isVariablyModifiedType());
4594 }
4595 
4596 /// Build a sizeof or alignof expression given a type operand.
4597 ExprResult
4599  SourceLocation OpLoc,
4600  UnaryExprOrTypeTrait ExprKind,
4601  SourceRange R) {
4602  if (!TInfo)
4603  return ExprError();
4604 
4605  QualType T = TInfo->getType();
4606 
4607  if (!T->isDependentType() &&
4608  CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4609  return ExprError();
4610 
4611  if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4612  if (auto *TT = T->getAs<TypedefType>()) {
4613  for (auto I = FunctionScopes.rbegin(),
4614  E = std::prev(FunctionScopes.rend());
4615  I != E; ++I) {
4616  auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4617  if (CSI == nullptr)
4618  break;
4619  DeclContext *DC = nullptr;
4620  if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4621  DC = LSI->CallOperator;
4622  else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4623  DC = CRSI->TheCapturedDecl;
4624  else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4625  DC = BSI->TheDecl;
4626  if (DC) {
4627  if (DC->containsDecl(TT->getDecl()))
4628  break;
4630  }
4631  }
4632  }
4633  }
4634 
4635  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4636  if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4637  TInfo->getType()->isVariablyModifiedType())
4638  TInfo = TransformToPotentiallyEvaluated(TInfo);
4639 
4640  return new (Context) UnaryExprOrTypeTraitExpr(
4641  ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4642 }
4643 
4644 /// Build a sizeof or alignof expression given an expression
4645 /// operand.
4646 ExprResult
4648  UnaryExprOrTypeTrait ExprKind) {
4650  if (PE.isInvalid())
4651  return ExprError();
4652 
4653  E = PE.get();
4654 
4655  // Verify that the operand is valid.
4656  bool isInvalid = false;
4657  if (E->isTypeDependent()) {
4658  // Delay type-checking for type-dependent expressions.
4659  } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4660  isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4661  } else if (ExprKind == UETT_VecStep) {
4663  } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4664  Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4665  isInvalid = true;
4666  } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4667  Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4668  isInvalid = true;
4669  } else {
4670  isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4671  }
4672 
4673  if (isInvalid)
4674  return ExprError();
4675 
4676  if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4678  if (PE.isInvalid()) return ExprError();
4679  E = PE.get();
4680  }
4681 
4682  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4683  return new (Context) UnaryExprOrTypeTraitExpr(
4684  ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4685 }
4686 
4687 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4688 /// expr and the same for @c alignof and @c __alignof
4689 /// Note that the ArgRange is invalid if isType is false.
4690 ExprResult
4692  UnaryExprOrTypeTrait ExprKind, bool IsType,
4693  void *TyOrEx, SourceRange ArgRange) {
4694  // If error parsing type, ignore.
4695  if (!TyOrEx) return ExprError();
4696 
4697  if (IsType) {
4698  TypeSourceInfo *TInfo;
4699  (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4700  return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4701  }
4702 
4703  Expr *ArgEx = (Expr *)TyOrEx;
4704  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4705  return Result;
4706 }
4707 
4709  bool IsReal) {
4710  if (V.get()->isTypeDependent())
4711  return S.Context.DependentTy;
4712 
4713  // _Real and _Imag are only l-values for normal l-values.
4714  if (V.get()->getObjectKind() != OK_Ordinary) {
4715  V = S.DefaultLvalueConversion(V.get());
4716  if (V.isInvalid())
4717  return QualType();
4718  }
4719 
4720  // These operators return the element type of a complex type.
4721  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4722  return CT->getElementType();
4723 
4724  // Otherwise they pass through real integer and floating point types here.
4725  if (V.get()->getType()->isArithmeticType())
4726  return V.get()->getType();
4727 
4728  // Test for placeholders.
4729  ExprResult PR = S.CheckPlaceholderExpr(V.get());
4730  if (PR.isInvalid()) return QualType();
4731  if (PR.get() != V.get()) {
4732  V = PR;
4733  return CheckRealImagOperand(S, V, Loc, IsReal);
4734  }
4735 
4736  // Reject anything else.
4737  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4738  << (IsReal ? "__real" : "__imag");
4739  return QualType();
4740 }
4741 
4742 
4743 
4744 ExprResult
4746  tok::TokenKind Kind, Expr *Input) {
4747  UnaryOperatorKind Opc;
4748  switch (Kind) {
4749  default: llvm_unreachable("Unknown unary op!");
4750  case tok::plusplus: Opc = UO_PostInc; break;
4751  case tok::minusminus: Opc = UO_PostDec; break;
4752  }
4753 
4754  // Since this might is a postfix expression, get rid of ParenListExprs.
4756  if (Result.isInvalid()) return ExprError();
4757  Input = Result.get();
4758 
4759  return BuildUnaryOp(S, OpLoc, Opc, Input);
4760 }
4761 
4762 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4763 ///
4764 /// \return true on error
4766  SourceLocation opLoc,
4767  Expr *op) {
4768  assert(op->getType()->isObjCObjectPointerType());
4770  !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4771  return false;
4772 
4773  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4774  << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4775  << op->getSourceRange();
4776  return true;
4777 }
4778 
4780  auto *BaseNoParens = Base->IgnoreParens();
4781  if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4782  return MSProp->getPropertyDecl()->getType()->isArrayType();
4783  return isa<MSPropertySubscriptExpr>(BaseNoParens);
4784 }
4785 
4786 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4787 // Typically this is DependentTy, but can sometimes be more precise.
4788 //
4789 // There are cases when we could determine a non-dependent type:
4790 // - LHS and RHS may have non-dependent types despite being type-dependent
4791 // (e.g. unbounded array static members of the current instantiation)
4792 // - one may be a dependent-sized array with known element type
4793 // - one may be a dependent-typed valid index (enum in current instantiation)
4794 //
4795 // We *always* return a dependent type, in such cases it is DependentTy.
4796 // This avoids creating type-dependent expressions with non-dependent types.
4797 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4799  const ASTContext &Ctx) {
4800  assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4801  QualType LTy = LHS->getType(), RTy = RHS->getType();
4802  QualType Result = Ctx.DependentTy;
4803  if (RTy->isIntegralOrUnscopedEnumerationType()) {
4804  if (const PointerType *PT = LTy->getAs<PointerType>())
4805  Result = PT->getPointeeType();
4806  else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4807  Result = AT->getElementType();
4808  } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4809  if (const PointerType *PT = RTy->getAs<PointerType>())
4810  Result = PT->getPointeeType();
4811  else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4812  Result = AT->getElementType();
4813  }
4814  // Ensure we return a dependent type.
4815  return Result->isDependentType() ? Result : Ctx.DependentTy;
4816 }
4817 
4818 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4819 
4821  SourceLocation lbLoc,
4822  MultiExprArg ArgExprs,
4823  SourceLocation rbLoc) {
4824 
4825  if (base && !base->getType().isNull() &&
4826  base->hasPlaceholderType(BuiltinType::OMPArraySection))
4827  return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4828  SourceLocation(), /*Length*/ nullptr,
4829  /*Stride=*/nullptr, rbLoc);
4830 
4831  // Since this might be a postfix expression, get rid of ParenListExprs.
4832  if (isa<ParenListExpr>(base)) {
4834  if (result.isInvalid())
4835  return ExprError();
4836  base = result.get();
4837  }
4838 
4839  // Check if base and idx form a MatrixSubscriptExpr.
4840  //
4841  // Helper to check for comma expressions, which are not allowed as indices for
4842  // matrix subscript expressions.
4843  auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4844  if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4845  Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4846  << SourceRange(base->getBeginLoc(), rbLoc);
4847  return true;
4848  }
4849  return false;
4850  };
4851  // The matrix subscript operator ([][])is considered a single operator.
4852  // Separating the index expressions by parenthesis is not allowed.
4853  if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4854  !isa<MatrixSubscriptExpr>(base)) {
4855  Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4856  << SourceRange(base->getBeginLoc(), rbLoc);
4857  return ExprError();
4858  }
4859  // If the base is a MatrixSubscriptExpr, try to create a new
4860  // MatrixSubscriptExpr.
4861  auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4862  if (matSubscriptE) {
4863  assert(ArgExprs.size() == 1);
4864  if (CheckAndReportCommaError(ArgExprs.front()))
4865  return ExprError();
4866 
4867  assert(matSubscriptE->isIncomplete() &&
4868  "base has to be an incomplete matrix subscript");
4869  return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4870  matSubscriptE->getRowIdx(),
4871  ArgExprs.front(), rbLoc);
4872  }
4873 
4874  // Handle any non-overload placeholder types in the base and index
4875  // expressions. We can't handle overloads here because the other
4876  // operand might be an overloadable type, in which case the overload
4877  // resolution for the operator overload should get the first crack
4878  // at the overload.
4879  bool IsMSPropertySubscript = false;
4880  if (base->getType()->isNonOverloadPlaceholderType()) {
4881  IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4882  if (!IsMSPropertySubscript) {
4883  ExprResult result = CheckPlaceholderExpr(base);
4884  if (result.isInvalid())
4885  return ExprError();
4886  base = result.get();
4887  }
4888  }
4889 
4890  // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4891  if (base->getType()->isMatrixType()) {
4892  assert(ArgExprs.size() == 1);
4893  if (CheckAndReportCommaError(ArgExprs.front()))
4894  return ExprError();
4895 
4896  return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4897  rbLoc);
4898  }
4899 
4900  if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4901  Expr *idx = ArgExprs[0];
4902  if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4903  (isa<CXXOperatorCallExpr>(idx) &&
4904  cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4905  Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4906  << SourceRange(base->getBeginLoc(), rbLoc);
4907  }
4908  }
4909 
4910  if (ArgExprs.size() == 1 &&
4911  ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4912  ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4913  if (result.isInvalid())
4914  return ExprError();
4915  ArgExprs[0] = result.get();
4916  } else {
4917  if (checkArgsForPlaceholders(*this, ArgExprs))
4918  return ExprError();
4919  }
4920 
4921  // Build an unanalyzed expression if either operand is type-dependent.
4922  if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4923  (base->isTypeDependent() ||
4925  return new (Context) ArraySubscriptExpr(
4926  base, ArgExprs.front(),
4927  getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4928  VK_LValue, OK_Ordinary, rbLoc);
4929  }
4930 
4931  // MSDN, property (C++)
4932  // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4933  // This attribute can also be used in the declaration of an empty array in a
4934  // class or structure definition. For example:
4935  // __declspec(property(get=GetX, put=PutX)) int x[];
4936  // The above statement indicates that x[] can be used with one or more array
4937  // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4938  // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4939  if (IsMSPropertySubscript) {
4940  assert(ArgExprs.size() == 1);
4941  // Build MS property subscript expression if base is MS property reference
4942  // or MS property subscript.
4943  return new (Context)
4944  MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4945  VK_LValue, OK_Ordinary, rbLoc);
4946  }
4947 
4948  // Use C++ overloaded-operator rules if either operand has record
4949  // type. The spec says to do this if either type is *overloadable*,
4950  // but enum types can't declare subscript operators or conversion
4951  // operators, so there's nothing interesting for overload resolution
4952  // to do if there aren't any record types involved.
4953  //
4954  // ObjC pointers have their own subscripting logic that is not tied
4955  // to overload resolution and so should not take this path.
4956  if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4957  ((base->getType()->isRecordType() ||
4958  (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4959  return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4960  }
4961 
4962  ExprResult Res =
4963  CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4964 
4965  if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4966  CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4967 
4968  return Res;
4969 }
4970 
4975  InitializationSequence InitSeq(*this, Entity, Kind, E);
4976  return InitSeq.Perform(*this, Entity, Kind, E);
4977 }
4978 
4980  Expr *ColumnIdx,
4981  SourceLocation RBLoc) {
4983  if (BaseR.isInvalid())
4984  return BaseR;
4985  Base = BaseR.get();
4986 
4987  ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4988  if (RowR.isInvalid())
4989  return RowR;
4990  RowIdx = RowR.get();
4991 
4992  if (!ColumnIdx)
4993  return new (Context) MatrixSubscriptExpr(
4994  Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4995 
4996  // Build an unanalyzed expression if any of the operands is type-dependent.
4997  if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4998  ColumnIdx->isTypeDependent())
4999  return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5000  Context.DependentTy, RBLoc);
5001 
5002  ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5003  if (ColumnR.isInvalid())
5004  return ColumnR;
5005  ColumnIdx = ColumnR.get();
5006 
5007  // Check that IndexExpr is an integer expression. If it is a constant
5008  // expression, check that it is less than Dim (= the number of elements in the
5009  // corresponding dimension).
5010  auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5011  bool IsColumnIdx) -> Expr * {
5012  if (!IndexExpr->getType()->isIntegerType() &&
5013  !IndexExpr->isTypeDependent()) {
5014  Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5015  << IsColumnIdx;
5016  return nullptr;
5017  }
5018 
5019  if (std::optional<llvm::APSInt> Idx =
5020  IndexExpr->getIntegerConstantExpr(Context)) {
5021  if ((*Idx < 0 || *Idx >= Dim)) {
5022  Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5023  << IsColumnIdx << Dim;
5024  return nullptr;
5025  }
5026  }
5027 
5028  ExprResult ConvExpr =
5030  assert(!ConvExpr.isInvalid() &&
5031  "should be able to convert any integer type to size type");
5032  return ConvExpr.get();
5033  };
5034 
5035  auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5036  RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5037  ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5038  if (!RowIdx || !ColumnIdx)
5039  return ExprError();
5040 
5041  return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5042  MTy->getElementType(), RBLoc);
5043 }
5044 
5045 void Sema::CheckAddressOfNoDeref(const Expr *E) {
5046  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5047  const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5048 
5049  // For expressions like `&(*s).b`, the base is recorded and what should be
5050  // checked.
5051  const MemberExpr *Member = nullptr;
5052  while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5053  StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5054 
5055  LastRecord.PossibleDerefs.erase(StrippedExpr);
5056 }
5057 
5058 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5059  if (isUnevaluatedContext())
5060  return;
5061 
5062  QualType ResultTy = E->getType();
5063  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5064 
5065  // Bail if the element is an array since it is not memory access.
5066  if (isa<ArrayType>(ResultTy))
5067  return;
5068 
5069  if (ResultTy->hasAttr(attr::NoDeref)) {
5070  LastRecord.PossibleDerefs.insert(E);
5071  return;
5072  }
5073 
5074  // Check if the base type is a pointer to a member access of a struct
5075  // marked with noderef.
5076  const Expr *Base = E->getBase();
5077  QualType BaseTy = Base->getType();
5078  if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5079  // Not a pointer access
5080  return;
5081 
5082  const MemberExpr *Member = nullptr;
5083  while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5084  Member->isArrow())
5085  Base = Member->getBase();
5086 
5087  if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5088  if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5089  LastRecord.PossibleDerefs.insert(E);
5090  }
5091 }
5092 
5094  Expr *LowerBound,
5095  SourceLocation ColonLocFirst,
5096  SourceLocation ColonLocSecond,
5097  Expr *Length, Expr *Stride,
5098  SourceLocation RBLoc) {
5099  if (Base->hasPlaceholderType() &&
5100  !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5102  if (Result.isInvalid())
5103  return ExprError();
5104  Base = Result.get();
5105  }
5106  if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5107  ExprResult Result = CheckPlaceholderExpr(LowerBound);
5108  if (Result.isInvalid())
5109  return ExprError();
5110  Result = DefaultLvalueConversion(Result.get());
5111  if (Result.isInvalid())
5112  return ExprError();
5113  LowerBound = Result.get();
5114  }
5115  if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5116  ExprResult Result = CheckPlaceholderExpr(Length);
5117  if (Result.isInvalid())
5118  return ExprError();
5119  Result = DefaultLvalueConversion(Result.get());
5120  if (Result.isInvalid())
5121  return ExprError();
5122  Length = Result.get();
5123  }
5124  if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5125  ExprResult Result = CheckPlaceholderExpr(Stride);
5126  if (Result.isInvalid())
5127  return ExprError();
5128  Result = DefaultLvalueConversion(Result.get());
5129  if (Result.isInvalid())
5130  return ExprError();
5131  Stride = Result.get();
5132  }
5133 
5134  // Build an unanalyzed expression if either operand is type-dependent.
5135  if (Base->isTypeDependent() ||
5136  (LowerBound &&
5137  (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5138  (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5139  (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5140  return new (Context) OMPArraySectionExpr(
5141  Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5142  OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5143  }
5144 
5145  // Perform default conversions.
5147  QualType ResultTy;
5148  if (OriginalTy->isAnyPointerType()) {
5149  ResultTy = OriginalTy->getPointeeType();
5150  } else if (OriginalTy->isArrayType()) {
5151  ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5152  } else {
5153  return ExprError(
5154  Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5155  << Base->getSourceRange());
5156  }
5157  // C99 6.5.2.1p1
5158  if (LowerBound) {
5159  auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5160  LowerBound);
5161  if (Res.isInvalid())
5162  return ExprError(Diag(LowerBound->getExprLoc(),
5163  diag::err_omp_typecheck_section_not_integer)
5164  << 0 << LowerBound->getSourceRange());
5165  LowerBound = Res.get();
5166 
5167  if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5168  LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5169  Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5170  << 0 << LowerBound->getSourceRange();
5171  }
5172  if (Length) {
5173  auto Res =
5175  if (Res.isInvalid())
5176  return ExprError(Diag(Length->getExprLoc(),
5177  diag::err_omp_typecheck_section_not_integer)
5178  << 1 << Length->getSourceRange());
5179  Length = Res.get();
5180 
5181  if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5182  Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5183  Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5184  << 1 << Length->getSourceRange();
5185  }
5186  if (Stride) {
5187  ExprResult Res =
5189  if (Res.isInvalid())
5190  return ExprError(Diag(Stride->getExprLoc(),
5191  diag::err_omp_typecheck_section_not_integer)
5192  << 1 << Stride->getSourceRange());
5193  Stride = Res.get();
5194 
5195  if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5196  Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5197  Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5198  << 1 << Stride->getSourceRange();
5199  }
5200 
5201  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5202  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5203  // type. Note that functions are not objects, and that (in C99 parlance)
5204  // incomplete types are not object types.
5205  if (ResultTy->isFunctionType()) {
5206  Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5207  << ResultTy << Base->getSourceRange();
5208  return ExprError();
5209  }
5210 
5211  if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5212  diag::err_omp_section_incomplete_type, Base))
5213  return ExprError();
5214 
5215  if (LowerBound && !OriginalTy->isAnyPointerType()) {
5216  Expr::EvalResult Result;
5217  if (LowerBound->EvaluateAsInt(Result, Context)) {
5218  // OpenMP 5.0, [2.1.5 Array Sections]
5219  // The array section must be a subset of the original array.
5220  llvm::APSInt LowerBoundValue = Result.Val.getInt();
5221  if (LowerBoundValue.isNegative()) {
5222  Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5223  << LowerBound->getSourceRange();
5224  return ExprError();
5225  }
5226  }
5227  }
5228 
5229  if (Length) {
5230  Expr::EvalResult Result;
5231  if (Length->EvaluateAsInt(Result, Context)) {
5232  // OpenMP 5.0, [2.1.5 Array Sections]
5233  // The length must evaluate to non-negative integers.
5234  llvm::APSInt LengthValue = Result.Val.getInt();
5235  if (LengthValue.isNegative()) {
5236  Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5237  << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5238  << Length->getSourceRange();
5239  return ExprError();
5240  }
5241  }
5242  } else if (ColonLocFirst.isValid() &&
5243  (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5244  !OriginalTy->isVariableArrayType()))) {
5245  // OpenMP 5.0, [2.1.5 Array Sections]
5246  // When the size of the array dimension is not known, the length must be
5247  // specified explicitly.
5248  Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5249  << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5250  return ExprError();
5251  }
5252 
5253  if (Stride) {
5254  Expr::EvalResult Result;
5255  if (Stride->EvaluateAsInt(Result, Context)) {
5256  // OpenMP 5.0, [2.1.5 Array Sections]
5257  // The stride must evaluate to a positive integer.
5258  llvm::APSInt StrideValue = Result.Val.getInt();
5259  if (!StrideValue.isStrictlyPositive()) {
5260  Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5261  << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5262  << Stride->getSourceRange();
5263  return ExprError();
5264  }
5265  }
5266  }
5267 
5268  if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5270  if (Result.isInvalid())
5271  return ExprError();
5272  Base = Result.get();
5273  }
5274  return new (Context) OMPArraySectionExpr(
5275  Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5276  OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5277 }
5278 
5280  SourceLocation RParenLoc,
5281  ArrayRef<Expr *> Dims,
5282  ArrayRef<SourceRange> Brackets) {
5283  if (Base->hasPlaceholderType()) {
5285  if (Result.isInvalid())
5286  return ExprError();
5287  Result = DefaultLvalueConversion(Result.get());
5288  if (Result.isInvalid())
5289  return ExprError();
5290  Base = Result.get();
5291  }
5292  QualType BaseTy = Base->getType();
5293  // Delay analysis of the types/expressions if instantiation/specialization is
5294  // required.
5295  if (!BaseTy->isPointerType() && Base->isTypeDependent())
5297  LParenLoc, RParenLoc, Dims, Brackets);
5298  if (!BaseTy->isPointerType() ||
5299  (!Base->isTypeDependent() &&
5300  BaseTy->getPointeeType()->isIncompleteType()))
5301  return ExprError(Diag(Base->getExprLoc(),
5302  diag::err_omp_non_pointer_type_array_shaping_base)
5303  << Base->getSourceRange());
5304 
5305  SmallVector<Expr *, 4> NewDims;
5306  bool ErrorFound = false;
5307  for (Expr *Dim : Dims) {
5308  if (Dim->hasPlaceholderType()) {
5309  ExprResult Result = CheckPlaceholderExpr(Dim);
5310  if (Result.isInvalid()) {
5311  ErrorFound = true;
5312  continue;
5313  }
5314  Result = DefaultLvalueConversion(Result.get());
5315  if (Result.isInvalid()) {
5316  ErrorFound = true;
5317  continue;
5318  }
5319  Dim = Result.get();
5320  }
5321  if (!Dim->isTypeDependent()) {
5322  ExprResult Result =
5323  PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5324  if (Result.isInvalid()) {
5325  ErrorFound = true;
5326  Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5327  << Dim->getSourceRange();
5328  continue;
5329  }
5330  Dim = Result.get();
5331  Expr::EvalResult EvResult;
5332  if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5333  // OpenMP 5.0, [2.1.4 Array Shaping]
5334  // Each si is an integral type expression that must evaluate to a
5335  // positive integer.
5336  llvm::APSInt Value = EvResult.Val.getInt();
5337  if (!Value.isStrictlyPositive()) {
5338  Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5339  << toString(Value, /*Radix=*/10, /*Signed=*/true)
5340  << Dim->getSourceRange();
5341  ErrorFound = true;
5342  continue;
5343  }
5344  }
5345  }
5346  NewDims.push_back(Dim);
5347  }
5348  if (ErrorFound)
5349  return ExprError();
5351  LParenLoc, RParenLoc, NewDims, Brackets);
5352 }
5353 
5355  SourceLocation LLoc, SourceLocation RLoc,
5358  bool IsCorrect = true;
5359  for (const OMPIteratorData &D : Data) {
5360  TypeSourceInfo *TInfo = nullptr;
5361  SourceLocation StartLoc;
5362  QualType DeclTy;
5363  if (!D.Type.getAsOpaquePtr()) {
5364  // OpenMP 5.0, 2.1.6 Iterators
5365  // In an iterator-specifier, if the iterator-type is not specified then
5366  // the type of that iterator is of int type.
5367  DeclTy = Context.IntTy;
5368  StartLoc = D.DeclIdentLoc;
5369  } else {
5370  DeclTy = GetTypeFromParser(D.Type, &TInfo);
5371  StartLoc = TInfo->getTypeLoc().getBeginLoc();
5372  }
5373 
5374  bool IsDeclTyDependent = DeclTy->isDependentType() ||
5375  DeclTy->containsUnexpandedParameterPack() ||
5376  DeclTy->isInstantiationDependentType();
5377  if (!IsDeclTyDependent) {
5378  if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5379  // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5380  // The iterator-type must be an integral or pointer type.
5381  Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5382  << DeclTy;
5383  IsCorrect = false;
5384  continue;
5385  }
5386  if (DeclTy.isConstant(Context)) {
5387  // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5388  // The iterator-type must not be const qualified.
5389  Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5390  << DeclTy;
5391  IsCorrect = false;
5392  continue;
5393  }
5394  }
5395 
5396  // Iterator declaration.
5397  assert(D.DeclIdent && "Identifier expected.");
5398  // Always try to create iterator declarator to avoid extra error messages
5399  // about unknown declarations use.
5400  auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5401  D.DeclIdent, DeclTy, TInfo, SC_None);
5402  VD->setImplicit();
5403  if (S) {
5404  // Check for conflicting previous declaration.
5405  DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5406  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5408  Previous.suppressDiagnostics();
5409  LookupName(Previous, S);
5410 
5411  FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5412  /*AllowInlineNamespace=*/false);
5413  if (!Previous.empty()) {
5414  NamedDecl *Old = Previous.getRepresentativeDecl();
5415  Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5416  Diag(Old->getLocation(), diag::note_previous_definition);
5417  } else {
5418  PushOnScopeChains(VD, S);
5419  }
5420  } else {
5421  CurContext->addDecl(VD);
5422  }
5423 
5424  /// Act on the iterator variable declaration.
5426 
5427  Expr *Begin = D.Range.Begin;
5428  if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5429  ExprResult BeginRes =
5431  Begin = BeginRes.get();
5432  }
5433  Expr *End = D.Range.End;
5434  if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5436  End = EndRes.get();
5437  }
5438  Expr *Step = D.Range.Step;
5439  if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5440  if (!Step->getType()->isIntegralType(Context)) {
5441  Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5442  << Step << Step->getSourceRange();
5443  IsCorrect = false;
5444  continue;
5445  }
5446  std::optional<llvm::APSInt> Result =
5448  // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5449  // If the step expression of a range-specification equals zero, the
5450  // behavior is unspecified.
5451  if (Result && Result->isZero()) {
5452  Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5453  << Step << Step->getSourceRange();
5454  IsCorrect = false;
5455  continue;
5456  }
5457  }
5458  if (!Begin || !End || !IsCorrect) {
5459  IsCorrect = false;
5460  continue;
5461  }
5462  OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5463  IDElem.IteratorDecl = VD;
5464  IDElem.AssignmentLoc = D.AssignLoc;
5465  IDElem.Range.Begin = Begin;
5466  IDElem.Range.End = End;
5467  IDElem.Range.Step = Step;
5468  IDElem.ColonLoc = D.ColonLoc;
5469  IDElem.SecondColonLoc = D.SecColonLoc;
5470  }
5471  if (!IsCorrect) {
5472  // Invalidate all created iterator declarations if error is found.
5473  for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5474  if (Decl *ID = D.IteratorDecl)
5475  ID->setInvalidDecl();
5476  }
5477  return ExprError();
5478  }
5480  if (!CurContext->isDependentContext()) {
5481  // Build number of ityeration for each iteration range.
5482  // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5483  // ((Begini-Stepi-1-Endi) / -Stepi);
5485  // (Endi - Begini)
5486  ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5487  D.Range.Begin);
5488  if(!Res.isUsable()) {
5489  IsCorrect = false;
5490  continue;
5491  }
5492  ExprResult St, St1;
5493  if (D.Range.Step) {
5494  St = D.Range.Step;
5495  // (Endi - Begini) + Stepi
5496  Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5497  if (!Res.isUsable()) {
5498  IsCorrect = false;
5499  continue;
5500  }
5501  // (Endi - Begini) + Stepi - 1
5502  Res =
5503  CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5504  ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5505  if (!Res.isUsable()) {
5506  IsCorrect = false;
5507  continue;
5508  }
5509  // ((Endi - Begini) + Stepi - 1) / Stepi
5510  Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5511  if (!Res.isUsable()) {
5512  IsCorrect = false;
5513  continue;
5514  }
5515  St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5516  // (Begini - Endi)
5517  ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5518  D.Range.Begin, D.Range.End);
5519  if (!Res1.isUsable()) {
5520  IsCorrect = false;
5521  continue;
5522  }
5523  // (Begini - Endi) - Stepi
5524  Res1 =
5525  CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5526  if (!Res1.isUsable()) {
5527  IsCorrect = false;
5528  continue;
5529  }
5530  // (Begini - Endi) - Stepi - 1
5531  Res1 =
5532  CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5533  ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5534  if (!Res1.isUsable()) {
5535  IsCorrect = false;
5536  continue;
5537  }
5538  // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5539  Res1 =
5540  CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5541  if (!Res1.isUsable()) {
5542  IsCorrect = false;
5543  continue;
5544  }
5545  // Stepi > 0.
5546  ExprResult CmpRes =
5547  CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5548  ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5549  if (!CmpRes.isUsable()) {
5550  IsCorrect = false;
5551  continue;
5552  }
5553  Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5554  Res.get(), Res1.get());
5555  if (!Res.isUsable()) {
5556  IsCorrect = false;
5557  continue;
5558  }
5559  }
5560  Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5561  if (!Res.isUsable()) {
5562  IsCorrect = false;
5563  continue;
5564  }
5565 
5566  // Build counter update.
5567  // Build counter.
5568  auto *CounterVD =
5569  VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5570  D.IteratorDecl->getBeginLoc(), nullptr,
5571  Res.get()->getType(), nullptr, SC_None);
5572  CounterVD->setImplicit();
5573  ExprResult RefRes =
5574  BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5575  D.IteratorDecl->getBeginLoc());
5576  // Build counter update.
5577  // I = Begini + counter * Stepi;
5578  ExprResult UpdateRes;
5579  if (D.Range.Step) {
5580  UpdateRes = CreateBuiltinBinOp(
5581  D.AssignmentLoc, BO_Mul,
5582  DefaultLvalueConversion(RefRes.get()).get(), St.get());
5583  } else {
5584  UpdateRes = DefaultLvalueConversion(RefRes.get());
5585  }
5586  if (!UpdateRes.isUsable()) {
5587  IsCorrect = false;
5588  continue;
5589  }
5590  UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5591  UpdateRes.get());
5592  if (!UpdateRes.isUsable()) {
5593  IsCorrect = false;
5594  continue;
5595  }
5596  ExprResult VDRes =
5597  BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5598  cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5599  D.IteratorDecl->getBeginLoc());
5600  UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5601  UpdateRes.get());
5602  if (!UpdateRes.isUsable()) {
5603  IsCorrect = false;
5604  continue;
5605  }
5606  UpdateRes =
5607  ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5608  if (!UpdateRes.isUsable()) {
5609  IsCorrect = false;
5610  continue;
5611  }
5612  ExprResult CounterUpdateRes =
5613  CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5614  if (!CounterUpdateRes.isUsable()) {
5615  IsCorrect = false;
5616  continue;
5617  }
5618  CounterUpdateRes =
5619  ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5620  if (!CounterUpdateRes.isUsable()) {
5621  IsCorrect = false;
5622  continue;
5623  }
5624  OMPIteratorHelperData &HD = Helpers.emplace_back();
5625  HD.CounterVD = CounterVD;
5626  HD.Upper = Res.get();
5627  HD.Update = UpdateRes.get();
5628  HD.CounterUpdate = CounterUpdateRes.get();
5629  }
5630  } else {
5631  Helpers.assign(ID.size(), {});
5632  }
5633  if (!IsCorrect) {
5634  // Invalidate all created iterator declarations if error is found.
5635  for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5636  if (Decl *ID = D.IteratorDecl)
5637  ID->setInvalidDecl();
5638  }
5639  return ExprError();
5640  }
5641  return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5642  LLoc, RLoc, ID, Helpers);
5643 }
5644 
5645 ExprResult
5647  Expr *Idx, SourceLocation RLoc) {
5648  Expr *LHSExp = Base;
5649  Expr *RHSExp = Idx;
5650 
5651  ExprValueKind VK = VK_LValue;
5653 
5654  // Per C++ core issue 1213, the result is an xvalue if either operand is
5655  // a non-lvalue array, and an lvalue otherwise.
5656  if (getLangOpts().CPlusPlus11) {
5657  for (auto *Op : {LHSExp, RHSExp}) {
5658  Op = Op->IgnoreImplicit();
5659  if (Op->getType()->isArrayType() && !Op->isLValue())
5660  VK = VK_XValue;
5661  }
5662  }
5663 
5664  // Perform default conversions.
5665  if (!LHSExp->getType()->getAs<VectorType>()) {
5667  if (Result.isInvalid())
5668  return ExprError();
5669  LHSExp = Result.get();
5670  }
5672  if (Result.isInvalid())
5673  return ExprError();
5674  RHSExp = Result.get();
5675 
5676  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5677 
5678  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5679  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5680  // in the subscript position. As a result, we need to derive the array base
5681  // and index from the expression types.
5682  Expr *BaseExpr, *IndexExpr;
5683  QualType ResultType;
5684  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5685  BaseExpr = LHSExp;
5686  IndexExpr = RHSExp;
5687  ResultType =
5688  getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5689  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5690  BaseExpr = LHSExp;
5691  IndexExpr = RHSExp;
5692  ResultType = PTy->getPointeeType();
5693  } else if (const ObjCObjectPointerType *PTy =
5694  LHSTy->getAs<ObjCObjectPointerType>()) {
5695  BaseExpr = LHSExp;
5696  IndexExpr = RHSExp;
5697 
5698  // Use custom logic if this should be the pseudo-object subscript
5699  // expression.
5701  return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5702  nullptr);
5703 
5704  ResultType = PTy->getPointeeType();
5705  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5706  // Handle the uncommon case of "123[Ptr]".
5707  BaseExpr = RHSExp;
5708  IndexExpr = LHSExp;
5709  ResultType = PTy->getPointeeType();
5710  } else if (const ObjCObjectPointerType *PTy =
5711  RHSTy->getAs<ObjCObjectPointerType>()) {
5712  // Handle the uncommon case of "123[Ptr]".
5713  BaseExpr = RHSExp;
5714  IndexExpr = LHSExp;
5715  ResultType = PTy->getPointeeType();
5717  Diag(LLoc, diag::err_subscript_nonfragile_interface)
5718  << ResultType << BaseExpr->getSourceRange();
5719  return ExprError();
5720  }
5721  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5722  BaseExpr = LHSExp; // vectors: V[123]
5723  IndexExpr = RHSExp;
5724  // We apply C++ DR1213 to vector subscripting too.
5725  if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5726  ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5727  if (Materialized.isInvalid())
5728  return ExprError();
5729  LHSExp = Materialized.get();
5730  }
5731  VK = LHSExp->getValueKind();
5732  if (VK != VK_PRValue)
5733  OK = OK_VectorComponent;
5734 
5735  ResultType = VTy->getElementType();
5736  QualType BaseType = BaseExpr->getType();
5737  Qualifiers BaseQuals = BaseType.getQualifiers();
5738  Qualifiers MemberQuals = ResultType.getQualifiers();
5739  Qualifiers Combined = BaseQuals + MemberQuals;
5740  if (Combined != MemberQuals)
5741  ResultType = Context.getQualifiedType(ResultType, Combined);
5742  } else if (LHSTy->isBuiltinType() &&
5743  LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) {
5744  const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5745  if (BTy->isSVEBool())
5746  return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5747  << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5748 
5749  BaseExpr = LHSExp;
5750  IndexExpr = RHSExp;
5751  if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5752  ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5753  if (Materialized.isInvalid())
5754  return ExprError();
5755  LHSExp = Materialized.get();
5756  }
5757  VK = LHSExp->getValueKind();
5758  if (VK != VK_PRValue)
5759  OK = OK_VectorComponent;
5760 
5761  ResultType = BTy->getSveEltType(Context);
5762 
5763  QualType BaseType = BaseExpr->getType();
5764  Qualifiers BaseQuals = BaseType.getQualifiers();
5765  Qualifiers MemberQuals = ResultType.getQualifiers();
5766  Qualifiers Combined = BaseQuals + MemberQuals;
5767  if (Combined != MemberQuals)
5768  ResultType = Context.getQualifiedType(ResultType, Combined);
5769  } else if (LHSTy->isArrayType()) {
5770  // If we see an array that wasn't promoted by
5771  // DefaultFunctionArrayLvalueConversion, it must be an array that
5772  // wasn't promoted because of the C90 rule that doesn't
5773  // allow promoting non-lvalue arrays. Warn, then
5774  // force the promotion here.
5775  Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5776  << LHSExp->getSourceRange();
5777  LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5778  CK_ArrayToPointerDecay).get();
5779  LHSTy = LHSExp->getType();
5780 
5781  BaseExpr = LHSExp;
5782  IndexExpr = RHSExp;
5783  ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5784  } else if (RHSTy->isArrayType()) {
5785  // Same as previous, except for 123[f().a] case
5786  Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5787  << RHSExp->getSourceRange();
5788  RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5789  CK_ArrayToPointerDecay).get();
5790  RHSTy = RHSExp->getType();
5791 
5792  BaseExpr = RHSExp;
5793  IndexExpr = LHSExp;
5794  ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5795  } else {
5796  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5797  << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5798  }
5799  // C99 6.5.2.1p1
5800  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5801  return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5802  << IndexExpr->getSourceRange());
5803 
5804  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5805  IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5806  && !IndexExpr->isTypeDependent())
5807  Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5808 
5809  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5810  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5811  // type. Note that Functions are not objects, and that (in C99 parlance)
5812  // incomplete types are not object types.
5813  if (ResultType->isFunctionType()) {
5814  Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5815  << ResultType << BaseExpr->getSourceRange();
5816  return ExprError();
5817  }
5818 
5819  if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5820  // GNU extension: subscripting on pointer to void
5821  Diag(LLoc, diag::ext_gnu_subscript_void_type)
5822  << BaseExpr->getSourceRange();
5823 
5824  // C forbids expressions of unqualified void type from being l-values.
5825  // See IsCForbiddenLValueType.
5826  if (!ResultType.hasQualifiers())
5827  VK = VK_PRValue;
5828  } else if (!ResultType->isDependentType() &&
5830  LLoc, ResultType,
5831  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5832  return ExprError();
5833 
5834  assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5835  !ResultType.isCForbiddenLValueType());
5836 
5837  if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5838  FunctionScopes.size() > 1) {
5839  if (auto *TT =
5840  LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5841  for (auto I = FunctionScopes.rbegin(),
5842  E = std::prev(FunctionScopes.rend());
5843  I != E; ++I) {
5844  auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5845  if (CSI == nullptr)
5846  break;
5847  DeclContext *DC = nullptr;
5848  if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5849  DC = LSI->CallOperator;
5850  else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5851  DC = CRSI->TheCapturedDecl;
5852  else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5853  DC = BSI->TheDecl;
5854  if (DC) {
5855  if (DC->containsDecl(TT->getDecl()))
5856  break;
5858  Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5859  }
5860  }
5861  }
5862  }
5863 
5864  return new (Context)
5865  ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5866 }
5867 
5869  ParmVarDecl *Param, Expr *RewrittenInit,
5870  bool SkipImmediateInvocations) {
5871  if (Param->hasUnparsedDefaultArg()) {
5872  assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5873  // If we've already cleared out the location for the default argument,
5874  // that means we're parsing it right now.
5875  if (!UnparsedDefaultArgLocs.count(Param)) {
5876  Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5877  Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5878  Param->setInvalidDecl();
5879  return true;
5880  }
5881 
5882  Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5883  << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5885  diag::note_default_argument_declared_here);
5886  return true;
5887  }
5888 
5889  if (Param->hasUninstantiatedDefaultArg()) {
5890  assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5891  if (InstantiateDefaultArgument(CallLoc, FD, Param))
5892  return true;
5893  }
5894 
5895  Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5896  assert(Init && "default argument but no initializer?");
5897 
5898  // If the default expression creates temporaries, we need to
5899  // push them to the current stack of expression temporaries so they'll
5900  // be properly destroyed.
5901  // FIXME: We should really be rebuilding the default argument with new
5902  // bound temporaries; see the comment in PR5810.
5903  // We don't need to do that with block decls, though, because
5904  // blocks in default argument expression can never capture anything.
5905  if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5906  // Set the "needs cleanups" bit regardless of whether there are
5907  // any explicit objects.
5908  Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5909  // Append all the objects to the cleanup list. Right now, this
5910  // should always be a no-op, because blocks in default argument
5911  // expressions should never be able to capture anything.
5912  assert(!InitWithCleanup->getNumObjects() &&
5913  "default argument expression has capturing blocks?");
5914  }
5917  ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5918  SkipImmediateInvocations;
5919  MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables*/ true);
5920  return false;
5921 }
5922 
5923 struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
5924  bool HasImmediateCalls = false;
5925 
5926  bool shouldVisitImplicitCode() const { return true; }
5927 
5929  if (const FunctionDecl *FD = E->getDirectCallee())
5930  HasImmediateCalls |= FD->isConsteval();
5932  }
5933 
5934  // SourceLocExpr are not immediate invocations
5935  // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5936  // need to be rebuilt so that they refer to the correct SourceLocation and
5937  // DeclContext.
5939  HasImmediateCalls = true;
5941  }
5942 
5943  // A nested lambda might have parameters with immediate invocations
5944  // in their default arguments.
5945  // The compound statement is not visited (as it does not constitute a
5946  // subexpression).
5947  // FIXME: We should consider visiting and transforming captures
5948  // with init expressions.
5950  return VisitCXXMethodDecl(E->getCallOperator());
5951  }
5952 
5953  // Blocks don't support default parameters, and, as for lambdas,
5954  // we don't consider their body a subexpression.
5955  bool VisitBlockDecl(BlockDecl *B) { return false; }
5956 
5957  bool VisitCompoundStmt(CompoundStmt *B) { return false; }
5958 
5960  return TraverseStmt(E->getExpr());
5961  }
5962 
5964  return TraverseStmt(E->getExpr());
5965  }
5966 };
5967 
5969  : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5971  : TreeTransform(SemaRef) {}
5972 
5973  // Lambda can only have immediate invocations in the default
5974  // args of their parameters, which is transformed upon calling the closure.
5975  // The body is not a subexpression, so we have nothing to do.
5976  // FIXME: Immediate calls in capture initializers should be transformed.
5979 
5980  // Make sure we don't rebuild the this pointer as it would
5981  // cause it to incorrectly point it to the outermost class
5982  // in the case of nested struct initialization.
5984 };
5985 
5987  FunctionDecl *FD, ParmVarDecl *Param,
5988  Expr *Init) {
5989  assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5990 
5991  bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5992 
5993  std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5994  InitializationContext =
5996  if (!InitializationContext.has_value())
5997  InitializationContext.emplace(CallLoc, Param, CurContext);
5998 
5999  if (!Init && !Param->hasUnparsedDefaultArg()) {
6000  // Mark that we are replacing a default argument first.
6001  // If we are instantiating a template we won't have to
6002  // retransform immediate calls.
6005 
6006  if (Param->hasUninstantiatedDefaultArg()) {
6007  if (InstantiateDefaultArgument(CallLoc, FD, Param))
6008  return ExprError();
6009  }
6010  // CWG2631
6011  // An immediate invocation that is not evaluated where it appears is
6012  // evaluated and checked for whether it is a constant expression at the
6013  // point where the enclosing initializer is used in a function call.
6015  if (!NestedDefaultChecking)
6016  V.TraverseDecl(Param);
6017  if (V.HasImmediateCalls) {
6018  ExprEvalContexts.back().DelayedDefaultInitializationContext = {
6019  CallLoc, Param, CurContext};
6020  EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6021  ExprResult Res = Immediate.TransformInitializer(Param->getInit(),
6022  /*NotCopy=*/false);
6023  if (Res.isInvalid())
6024  return ExprError();
6025  Res = ConvertParamDefaultArgument(Param, Res.get(),
6026  Res.get()->getBeginLoc());
6027  if (Res.isInvalid())
6028  return ExprError();
6029  Init = Res.get();
6030  }
6031  }
6032 
6034  CallLoc, FD, Param, Init,
6035  /*SkipImmediateInvocations=*/NestedDefaultChecking))
6036  return ExprError();
6037 
6038  return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
6039  Init, InitializationContext->Context);
6040 }
6041 
6043  assert(Field->hasInClassInitializer());
6044 
6045  // If we might have already tried and failed to instantiate, don't try again.
6046  if (Field->isInvalidDecl())
6047  return ExprError();
6048 
6049  auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
6050 
6051  std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6052  InitializationContext =
6054  if (!InitializationContext.has_value())
6055  InitializationContext.emplace(Loc, Field, CurContext);
6056 
6057  Expr *Init = nullptr;
6058 
6059  bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6060 
6063 
6064  if (!Field->getInClassInitializer()) {
6065  // Maybe we haven't instantiated the in-class initializer. Go check the
6066  // pattern FieldDecl to see if it has one.
6067  if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
6068  CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
6070  ClassPattern->lookup(Field->getDeclName());
6071 
6072  FieldDecl *Pattern = nullptr;
6073  for (auto *L : Lookup) {
6074  if ((Pattern = dyn_cast<FieldDecl>(L)))
6075  break;
6076  }
6077  assert(Pattern && "We must have set the Pattern!");
6078  if (!Pattern->hasInClassInitializer() ||
6079  InstantiateInClassInitializer(Loc, Field, Pattern,
6080  getTemplateInstantiationArgs(Field))) {
6081  Field->setInvalidDecl();
6082  return ExprError();
6083  }
6084  }
6085  }
6086 
6087  // CWG2631
6088  // An immediate invocation that is not evaluated where it appears is
6089  // evaluated and checked for whether it is a constant expression at the
6090  // point where the enclosing initializer is used in a [...] a constructor
6091  // definition, or an aggregate initialization.
6093  if (!NestedDefaultChecking)
6094  V.TraverseDecl(Field);
6095  if (V.HasImmediateCalls) {
6096  ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
6097  CurContext};
6098  ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6099  NestedDefaultChecking;
6100 
6101  EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6102 
6103  ExprResult Res =
6104  Immediate.TransformInitializer(Field->getInClassInitializer(),
6105  /*CXXDirectInit=*/false);
6106  if (!Res.isInvalid())
6107  Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
6108  if (Res.isInvalid()) {
6109  Field->setInvalidDecl();
6110  return ExprError();
6111  }
6112  Init = Res.get();
6113  }
6114 
6115  if (Field->getInClassInitializer()) {
6116  Expr *E = Init ? Init : Field->getInClassInitializer();
6117  if (!NestedDefaultChecking)
6118  MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
6119  // C++11 [class.base.init]p7:
6120  // The initialization of each base and member constitutes a
6121  // full-expression.
6122  ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
6123  if (Res.isInvalid()) {
6124  Field->setInvalidDecl();
6125  return ExprError();
6126  }
6127  Init = Res.get();
6128 
6129  return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
6130  Field, InitializationContext->Context,
6131  Init);
6132  }
6133 
6134  // DR1351:
6135  // If the brace-or-equal-initializer of a non-static data member
6136  // invokes a defaulted default constructor of its class or of an
6137  // enclosing class in a potentially evaluated subexpression, the
6138  // program is ill-formed.
6139  //
6140  // This resolution is unworkable: the exception specification of the
6141  // default constructor can be needed in an unevaluated context, in
6142  // particular, in the operand of a noexcept-expression, and we can be
6143  // unable to compute an exception specification for an enclosed class.
6144  //
6145  // Any attempt to resolve the exception specification of a defaulted default
6146  // constructor before the initializer is lexically complete will ultimately
6147  // come here at which point we can diagnose it.
6148  RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6149  Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
6150  << OutermostClass << Field;
6151  Diag(Field->getEndLoc(),
6152  diag::note_default_member_initializer_not_yet_parsed);
6153  // Recover by marking the field invalid, unless we're in a SFINAE context.
6154  if (!isSFINAEContext())
6155  Field->setInvalidDecl();
6156  return ExprError();
6157 }
6158 
6161  Expr *Fn) {
6162  if (Proto && Proto->isVariadic()) {
6163  if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
6164  return VariadicConstructor;
6165  else if (Fn && Fn->getType()->isBlockPointerType())
6166  return VariadicBlock;
6167  else if (FDecl) {
6168  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6169  if (Method->isInstance())
6170  return VariadicMethod;
6171  } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6172  return VariadicMethod;
6173  return VariadicFunction;
6174  }
6175  return VariadicDoesNotApply;
6176 }
6177 
6178 namespace {
6179 class FunctionCallCCC final : public FunctionCallFilterCCC {
6180 public:
6181  FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6182  unsigned NumArgs, MemberExpr *ME)
6183  : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6184  FunctionName(FuncName) {}
6185 
6186  bool ValidateCandidate(const TypoCorrection &candidate) override {
6187  if (!candidate.getCorrectionSpecifier() ||
6188  candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6189  return false;
6190  }
6191 
6192  return FunctionCallFilterCCC::ValidateCandidate(candidate);
6193  }
6194 
6195  std::unique_ptr<CorrectionCandidateCallback> clone() override {
6196  return std::make_unique<FunctionCallCCC>(*this);
6197  }
6198 
6199 private:
6200  const IdentifierInfo *const FunctionName;
6201 };
6202 }
6203 
6205  FunctionDecl *FDecl,
6206  ArrayRef<Expr *> Args) {
6207  MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6208  DeclarationName FuncName = FDecl->getDeclName();
6209  SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6210 
6211  FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6212  if (TypoCorrection Corrected = S.CorrectTypo(
6213  DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
6214  S.getScopeForContext(S.CurContext), nullptr, CCC,
6216  if (NamedDecl *ND = Corrected.getFoundDecl()) {
6217  if (Corrected.isOverloaded()) {
6220  for (NamedDecl *CD : Corrected) {
6221  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6223  OCS);
6224  }
6225  switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6226  case OR_Success:
6227  ND = Best->FoundDecl;
6228  Corrected.setCorrectionDecl(ND);
6229  break;
6230  default:
6231  break;
6232  }
6233  }
6234  ND = ND->getUnderlyingDecl();
6235  if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
6236  return Corrected;
6237  }
6238  }
6239  return TypoCorrection();
6240 }
6241 
6242 /// ConvertArgumentsForCall - Converts the arguments specified in
6243 /// Args/NumArgs to the parameter types of the function FDecl with
6244 /// function prototype Proto. Call is the call expression itself, and
6245 /// Fn is the function expression. For a C++ member function, this
6246 /// routine does not attempt to convert the object argument. Returns
6247 /// true if the call is ill-formed.
6248 bool
6250  FunctionDecl *FDecl,
6251  const FunctionProtoType *Proto,
6252  ArrayRef<Expr *> Args,
6253  SourceLocation RParenLoc,
6254  bool IsExecConfig) {
6255  // Bail out early if calling a builtin with custom typechecking.
6256  if (FDecl)
6257  if (unsigned ID = FDecl->getBuiltinID())
6259  return false;
6260 
6261  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6262  // assignment, to the types of the corresponding parameter, ...
6263  unsigned NumParams = Proto->getNumParams();
6264  bool Invalid = false;
6265  unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6266  unsigned FnKind = Fn->getType()->isBlockPointerType()
6267  ? 1 /* block */
6268  : (IsExecConfig ? 3 /* kernel function (exec config) */
6269  : 0 /* function */);
6270 
6271  // If too few arguments are available (and we don't have default
6272  // arguments for the remaining parameters), don't make the call.
6273  if (Args.size() < NumParams) {
6274  if (Args.size() < MinArgs) {
6275  TypoCorrection TC;
6276  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6277  unsigned diag_id =
6278  MinArgs == NumParams && !Proto->isVariadic()
6279  ? diag::err_typecheck_call_too_few_args_suggest
6280  : diag::err_typecheck_call_too_few_args_at_least_suggest;
6281  diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
6282  << static_cast<unsigned>(Args.size())
6283  << TC.getCorrectionRange());
6284  } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
6285  Diag(RParenLoc,
6286  MinArgs == NumParams && !Proto->isVariadic()
6287  ? diag::err_typecheck_call_too_few_args_one
6288  : diag::err_typecheck_call_too_few_args_at_least_one)
6289  << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
6290  else
6291  Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6292  ? diag::err_typecheck_call_too_few_args
6293  : diag::err_typecheck_call_too_few_args_at_least)
6294  << FnKind << MinArgs << static_cast<unsigned>(Args.size())
6295  << Fn->getSourceRange();
6296 
6297  // Emit the location of the prototype.
6298  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6299  Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6300 
6301  return true;
6302  }
6303  // We reserve space for the default arguments when we create
6304  // the call expression, before calling ConvertArgumentsForCall.
6305  assert((Call->getNumArgs() == NumParams) &&
6306  "We should have reserved space for the default arguments before!");
6307  }
6308 
6309  // If too many are passed and not variadic, error on the extras and drop
6310  // them.
6311  if (Args.size() > NumParams) {
6312  if (!Proto->isVariadic()) {
6313  TypoCorrection TC;
6314  if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6315  unsigned diag_id =
6316  MinArgs == NumParams && !Proto->isVariadic()
6317  ? diag::err_typecheck_call_too_many_args_suggest
6318  : diag::err_typecheck_call_too_many_args_at_most_suggest;
6319  diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6320  << static_cast<unsigned>(Args.size())
6321  << TC.getCorrectionRange());
6322  } else if (NumParams == 1 && FDecl &&
6323  FDecl->getParamDecl(0)->getDeclName())
6324  Diag(Args[NumParams]->getBeginLoc(),
6325  MinArgs == NumParams
6326  ? diag::err_typecheck_call_too_many_args_one
6327  : diag::err_typecheck_call_too_many_args_at_most_one)
6328  << FnKind << FDecl->getParamDecl(0)
6329  << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6330  << SourceRange(Args[NumParams]->getBeginLoc(),
6331  Args.back()->getEndLoc());
6332  else
6333  Diag(Args[NumParams]->getBeginLoc(),
6334  MinArgs == NumParams
6335  ? diag::err_typecheck_call_too_many_args
6336  : diag::err_typecheck_call_too_many_args_at_most)
6337  << FnKind << NumParams << static_cast<unsigned>(Args.size())
6338  << Fn->getSourceRange()
6339  << SourceRange(Args[NumParams]->getBeginLoc(),
6340  Args.back()->getEndLoc());
6341 
6342  // Emit the location of the prototype.
6343  if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6344  Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6345 
6346  // This deletes the extra arguments.
6347  Call->shrinkNumArgs(NumParams);
6348  return true;
6349  }
6350  }
6351  SmallVector<Expr *, 8> AllArgs;
6352  VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6353 
6354  Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6355  AllArgs, CallType);
6356  if (Invalid)
6357  return true;
6358  unsigned TotalNumArgs = AllArgs.size();
6359  for (unsigned i = 0; i < TotalNumArgs; ++i)
6360  Call->setArg(i, AllArgs[i]);
6361 
6362  Call->computeDependence();
6363  return false;
6364 }
6365 
6367  const FunctionProtoType *Proto,
6368  unsigned FirstParam, ArrayRef<Expr *> Args,
6369  SmallVectorImpl<Expr *> &AllArgs,
6370  VariadicCallType CallType, bool AllowExplicit,
6371  bool IsListInitialization) {
6372  unsigned NumParams = Proto->getNumParams();
6373  bool Invalid = false;
6374  size_t ArgIx = 0;
6375  // Continue to check argument types (even if we have too few/many args).
6376  for (unsigned i = FirstParam; i < NumParams; i++) {
6377  QualType ProtoArgType = Proto->getParamType(i);
6378 
6379  Expr *Arg;
6380  ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6381  if (ArgIx < Args.size()) {
6382  Arg = Args[ArgIx++];
6383 
6384  if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6385  diag::err_call_incomplete_argument, Arg))
6386  return true;
6387 
6388  // Strip the unbridged-cast placeholder expression off, if applicable.
6389  bool CFAudited = false;
6390  if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6391  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6392  (!Param || !Param->hasAttr<CFConsumedAttr>()))
6393  Arg = stripARCUnbridgedCast(Arg);
6394  else if (getLangOpts().ObjCAutoRefCount &&
6395  FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6396  (!Param || !Param->hasAttr<CFConsumedAttr>()))
6397  CFAudited = true;
6398 
6399  if (Proto->getExtParameterInfo(i).isNoEscape() &&
6400  ProtoArgType->isBlockPointerType())
6401  if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6402  BE->getBlockDecl()->setDoesNotEscape();
6403 
6404  InitializedEntity Entity =
6406  ProtoArgType)
6408  Context, ProtoArgType, Proto->isParamConsumed(i));
6409 
6410  // Remember that parameter belongs to a CF audited API.
6411  if (CFAudited)
6412  Entity.setParameterCFAudited();
6413 
6415  Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6416  if (ArgE.isInvalid())
6417  return true;
6418 
6419  Arg = ArgE.getAs<Expr>();
6420  } else {
6421  assert(Param && "can't use default arguments without a known callee");
6422 
6423  ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6424  if (ArgExpr.isInvalid())
6425  return true;
6426 
6427  Arg = ArgExpr.getAs<Expr>();
6428  }
6429 
6430  // Check for array bounds violations for each argument to the call. This
6431  // check only triggers warnings when the argument isn't a more complex Expr
6432  // with its own checking, such as a BinaryOperator.
6433  CheckArrayAccess(Arg);
6434 
6435  // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6436  CheckStaticArrayArgument(CallLoc, Param, Arg);
6437 
6438  AllArgs.push_back(Arg);
6439  }
6440 
6441  // If this is a variadic call, handle args passed through "...".
6442  if (CallType != VariadicDoesNotApply) {
6443  // Assume that extern "C" functions with variadic arguments that
6444  // return __unknown_anytype aren't *really* variadic.
6445  if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6446  FDecl->isExternC()) {
6447  for (Expr *A : Args.slice(ArgIx)) {
6448  QualType paramType; // ignored
6449  ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6450  Invalid |= arg.isInvalid();
6451  AllArgs.push_back(arg.get());
6452  }
6453 
6454  // Otherwise do argument promotion, (C99 6.5.2.2p7).
6455  } else {
6456  for (Expr *A : Args.slice(ArgIx)) {
6457  ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6458  Invalid |= Arg.isInvalid();
6459  AllArgs.push_back(Arg.get());
6460  }
6461  }
6462 
6463  // Check for array bounds violations.
6464  for (Expr *A : Args.slice(ArgIx))
6465  CheckArrayAccess(A);
6466  }
6467  return Invalid;
6468 }
6469 
6471  TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6472  if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6473  TL = DTL.getOriginalLoc();
6474  if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6475  S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6476  << ATL.getLocalSourceRange();
6477 }
6478 
6479 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6480 /// array parameter, check that it is non-null, and that if it is formed by
6481 /// array-to-pointer decay, the underlying array is sufficiently large.
6482 ///
6483 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6484 /// array type derivation, then for each call to the function, the value of the
6485 /// corresponding actual argument shall provide access to the first element of
6486 /// an array with at least as many elements as specified by the size expression.
6487 void
6489  ParmVarDecl *Param,
6490  const Expr *ArgExpr) {
6491  // Static array parameters are not supported in C++.
6492  if (!Param || getLangOpts().CPlusPlus)
6493  return;
6494 
6495  QualType OrigTy = Param->getOriginalType();
6496 
6497  const ArrayType *AT = Context.getAsArrayType(OrigTy);
6498  if (!AT || AT->getSizeModifier() != ArrayType::Static)
6499  return;
6500 
6501  if (ArgExpr->isNullPointerConstant(Context,
6503  Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6504  DiagnoseCalleeStaticArrayParam(*this, Param);
6505  return;
6506  }
6507 
6508  const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6509  if (!CAT)
6510  return;
6511 
6512  const ConstantArrayType *ArgCAT =
6514  if (!ArgCAT)
6515  return;
6516 
6517  if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6518  ArgCAT->getElementType())) {
6519  if (ArgCAT->getSize().ult(CAT->getSize())) {
6520  Diag(CallLoc, diag::warn_static_array_too_small)
6521  << ArgExpr->getSourceRange()
6522  << (unsigned)ArgCAT->getSize().getZExtValue()
6523  << (unsigned)CAT->getSize().getZExtValue() << 0;
6524  DiagnoseCalleeStaticArrayParam(*this, Param);
6525  }
6526  return;
6527  }
6528 
6529  std::optional<CharUnits> ArgSize =
6531  std::optional<CharUnits> ParmSize =
6533  if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6534  Diag(CallLoc, diag::warn_static_array_too_small)
6535  << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6536  << (unsigned)ParmSize->getQuantity() << 1;
6537  DiagnoseCalleeStaticArrayParam(*this, Param);
6538  }
6539 }
6540 
6541 /// Given a function expression of unknown-any type, try to rebuild it
6542 /// to have a function type.
6544 
6545 /// Is the given type a placeholder that we need to lower out
6546 /// immediately during argument processing?
6548  // Placeholders are never sugared.
6549  const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6550  if (!placeholder) return false;
6551 
6552  switch (placeholder->getKind()) {
6553  // Ignore all the non-placeholder types.
6554 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6555  case BuiltinType::Id:
6556 #include "clang/Basic/OpenCLImageTypes.def"
6557 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6558  case BuiltinType::Id:
6559 #include "clang/Basic/OpenCLExtensionTypes.def"
6560  // In practice we'll never use this, since all SVE types are sugared
6561  // via TypedefTypes rather than exposed directly as BuiltinTypes.
6562 #define SVE_TYPE(Name, Id, SingletonId) \
6563  case BuiltinType::Id:
6564 #include "clang/Basic/AArch64SVEACLETypes.def"
6565 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6566  case BuiltinType::Id:
6567 #include "clang/Basic/PPCTypes.def"
6568 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6569 #include "clang/Basic/RISCVVTypes.def"
6570 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6571 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6572 #include "clang/AST/BuiltinTypes.def"
6573  return false;
6574 
6575  // We cannot lower out overload sets; they might validly be resolved
6576  // by the call machinery.
6577  case BuiltinType::Overload:
6578  return false;
6579 
6580  // Unbridged casts in ARC can be handled in some call positions and
6581  // should be left in place.
6582  case BuiltinType::ARCUnbridgedCast:
6583  return false;
6584 
6585  // Pseudo-objects should be converted as soon as possible.
6586  case BuiltinType::PseudoObject:
6587  return true;
6588 
6589  // The debugger mode could theoretically but currently does not try
6590  // to resolve unknown-typed arguments based on known parameter types.
6591  case BuiltinType::UnknownAny:
6592  return true;
6593 
6594  // These are always invalid as call arguments and should be reported.
6595  case BuiltinType::BoundMember:
6596  case BuiltinType::BuiltinFn:
6597  case BuiltinType::IncompleteMatrixIdx:
6598  case BuiltinType::OMPArraySection:
6599  case BuiltinType::OMPArrayShaping:
6600  case BuiltinType::OMPIterator:
6601  return true;
6602 
6603  }
6604  llvm_unreachable("bad builtin type kind");
6605 }
6606 
6607 /// Check an argument list for placeholders that we won't try to
6608 /// handle later.
6610  // Apply this processing to all the arguments at once instead of
6611  // dying at the first failure.
6612  bool hasInvalid = false;
6613  for (size_t i = 0, e = args.size(); i != e; i++) {
6614  if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6615  ExprResult result = S.CheckPlaceholderExpr(args[i]);
6616  if (result.isInvalid()) hasInvalid = true;
6617  else args[i] = result.get();
6618  }
6619  }
6620  return hasInvalid;
6621 }
6622 
6623 /// If a builtin function has a pointer argument with no explicit address
6624 /// space, then it should be able to accept a pointer to any address
6625 /// space as input. In order to do this, we need to replace the
6626 /// standard builtin declaration with one that uses the same address space
6627 /// as the call.
6628 ///
6629 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6630 /// it does not contain any pointer arguments without
6631 /// an address space qualifer. Otherwise the rewritten
6632 /// FunctionDecl is returned.
6633 /// TODO: Handle pointer return types.
6635  FunctionDecl *FDecl,
6636  MultiExprArg ArgExprs) {
6637 
6638  QualType DeclType = FDecl->getType();
6639  const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6640 
6641  if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6642  ArgExprs.size() < FT->getNumParams())
6643  return nullptr;
6644 
6645  bool NeedsNewDecl = false;
6646  unsigned i = 0;
6647  SmallVector<QualType, 8> OverloadParams;
6648 
6649  for (QualType ParamType : FT->param_types()) {
6650 
6651  // Convert array arguments to pointer to simplify type lookup.
6652  ExprResult ArgRes =
6654  if (ArgRes.isInvalid())
6655  return nullptr;
6656  Expr *Arg = ArgRes.get();
6657  QualType ArgType = Arg->getType();
6658  if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6659  !ArgType->isPointerType() ||
6660  !ArgType->getPointeeType().hasAddressSpace() ||
6662  OverloadParams.push_back(ParamType);
6663  continue;
6664  }
6665 
6666  QualType PointeeType = ParamType->getPointeeType();
6667  if (PointeeType.hasAddressSpace())
6668  continue;
6669 
6670  NeedsNewDecl = true;
6671  LangAS AS = ArgType->getPointeeType().getAddressSpace();
6672 
6673  PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6674  OverloadParams.push_back(Context.getPointerType(PointeeType));
6675  }
6676 
6677  if (!NeedsNewDecl)
6678  return nullptr;
6679 
6681  EPI.Variadic = FT->isVariadic();
6682  QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6683  OverloadParams, EPI);
6684  DeclContext *Parent = FDecl->getParent();
6685  FunctionDecl *OverloadDecl = FunctionDecl::Create(
6686  Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6687  FDecl->getIdentifier(), OverloadTy,
6688  /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6689  false,
6690  /*hasPrototype=*/true);
6692  FT = cast<FunctionProtoType>(OverloadTy);
6693  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6694  QualType ParamType = FT->getParamType(i);
6695  ParmVarDecl *Parm =
6696  ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6697  SourceLocation(), nullptr, ParamType,
6698  /*TInfo=*/nullptr, SC_None, nullptr);
6699  Parm->setScopeInfo(0, i);
6700  Params.push_back(Parm);
6701  }
6702  OverloadDecl->setParams(Params);
6703  Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6704  return OverloadDecl;
6705 }
6706 
6707 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6708  FunctionDecl *Callee,
6709  MultiExprArg ArgExprs) {
6710  // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6711  // similar attributes) really don't like it when functions are called with an
6712  // invalid number of args.
6713  if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6714  /*PartialOverloading=*/false) &&
6715  !Callee->isVariadic())
6716  return;
6717  if (Callee->getMinRequiredArguments() > ArgExprs.size())
6718  return;
6719 
6720  if (const EnableIfAttr *Attr =
6721  S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6722  S.Diag(Fn->getBeginLoc(),
6723  isa<CXXMethodDecl>(Callee)
6724  ? diag::err_ovl_no_viable_member_function_in_call
6725  : diag::err_ovl_no_viable_function_in_call)
6726  << Callee << Callee->getSourceRange();
6727  S.Diag(Callee->getLocation(),
6728  diag::note_ovl_candidate_disabled_by_function_cond_attr)
6729  << Attr->getCond()->getSourceRange() << Attr->getMessage();
6730  return;
6731  }
6732 }
6733 
6735  const UnresolvedMemberExpr *const UME, Sema &S) {
6736 
6737  const auto GetFunctionLevelDCIfCXXClass =
6738  [](Sema &S) -> const CXXRecordDecl * {
6739  const DeclContext *const DC = S.getFunctionLevelDeclContext();
6740  if (!DC || !DC->getParent())
6741  return nullptr;
6742 
6743  // If the call to some member function was made from within a member
6744  // function body 'M' return return 'M's parent.
6745  if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6746  return MD->getParent()->getCanonicalDecl();
6747  // else the call was made from within a default member initializer of a
6748  // class, so return the class.
6749  if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6750  return RD->getCanonicalDecl();
6751  return nullptr;
6752  };
6753  // If our DeclContext is neither a member function nor a class (in the
6754  // case of a lambda in a default member initializer), we can't have an
6755  // enclosing 'this'.
6756 
6757  const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6758  if (!CurParentClass)
6759  return false;
6760 
6761  // The naming class for implicit member functions call is the class in which
6762  // name lookup starts.
6763  const CXXRecordDecl *const NamingClass =
6764  UME->getNamingClass()->getCanonicalDecl();
6765  assert(NamingClass && "Must have naming class even for implicit access");
6766 
6767  // If the unresolved member functions were found in a 'naming class' that is
6768  // related (either the same or derived from) to the class that contains the
6769  // member function that itself contained the implicit member access.
6770 
6771  return CurParentClass == NamingClass ||
6772  CurParentClass->isDerivedFrom(NamingClass);
6773 }
6774 
6775 static void
6777  Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6778 
6779  if (!UME)
6780  return;
6781 
6782  LambdaScopeInfo *const CurLSI = S.getCurLambda();
6783  // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6784  // already been captured, or if this is an implicit member function call (if
6785  // it isn't, an attempt to capture 'this' should already have been made).
6786  if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6787  !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6788  return;
6789 
6790  // Check if the naming class in which the unresolved members were found is
6791  // related (same as or is a base of) to the enclosing class.
6792 
6794  return;
6795 
6796 
6797  DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6798  // If the enclosing function is not dependent, then this lambda is
6799  // capture ready, so if we can capture this, do so.
6800  if (!EnclosingFunctionCtx->isDependentContext()) {
6801  // If the current lambda and all enclosing lambdas can capture 'this' -
6802  // then go ahead and capture 'this' (since our unresolved overload set
6803  // contains at least one non-static member function).
6804  if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6805  S.CheckCXXThisCapture(CallLoc);
6806  } else if (S.CurContext->isDependentContext()) {
6807  // ... since this is an implicit member reference, that might potentially
6808  // involve a 'this' capture, mark 'this' for potential capture in
6809  // enclosing lambdas.
6810  if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6811  CurLSI->addPotentialThisCapture(CallLoc);
6812  }
6813 }
6814 
6815 // Once a call is fully resolved, warn for unqualified calls to specific
6816 // C++ standard functions, like move and forward.
6818  // We are only checking unary move and forward so exit early here.
6819  if (Call->getNumArgs() != 1)
6820  return;
6821 
6822  Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6823  if (!E || isa<UnresolvedLookupExpr>(E))
6824  return;
6825  DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6826  if (!DRE || !DRE->getLocation().isValid())
6827  return;
6828 
6829  if (DRE->getQualifier())
6830  return;
6831 
6832  const FunctionDecl *FD = Call->getDirectCallee();
6833  if (!FD)
6834  return;
6835 
6836  // Only warn for some functions deemed more frequent or problematic.
6837  unsigned BuiltinID = FD->getBuiltinID();
6838  if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6839  return;
6840 
6841  S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6842  << FD->getQualifiedNameAsString()
6843  << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6844 }
6845 
6847  MultiExprArg ArgExprs, SourceLocation RParenLoc,
6848  Expr *ExecConfig) {
6849  ExprResult Call =
6850  BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6851  /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6852  if (Call.isInvalid())
6853  return Call;
6854 
6855  // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6856  // language modes.
6857  if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6858  if (ULE->hasExplicitTemplateArgs() &&
6859  ULE->decls_begin() == ULE->decls_end()) {
6861  ? diag::warn_cxx17_compat_adl_only_template_id
6862  : diag::ext_adl_only_template_id)
6863  << ULE->getName();
6864  }
6865  }
6866 
6867  if (LangOpts.OpenMP)
6868  Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6869  ExecConfig);
6870  if (LangOpts.CPlusPlus) {
6871  CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6872  if (CE)
6874  }
6875  return Call;
6876 }
6877 
6878 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6879 /// This provides the location of the left/right parens and a list of comma
6880 /// locations.
6882  MultiExprArg ArgExprs, SourceLocation RParenLoc,
6883  Expr *ExecConfig, bool IsExecConfig,
6884  bool AllowRecovery) {
6885  // Since this might be a postfix expression, get rid of ParenListExprs.
6887  if (Result.isInvalid()) return ExprError();
6888  Fn = Result.get();
6889 
6890  if (checkArgsForPlaceholders(*this, ArgExprs))
6891  return ExprError();
6892 
6893  if (getLangOpts().CPlusPlus) {
6894  // If this is a pseudo-destructor expression, build the call immediately.
6895  if (isa<CXXPseudoDestructorExpr>(Fn)) {
6896  if (!ArgExprs.empty()) {
6897  // Pseudo-destructor calls should not have any arguments.
6898  Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6900  SourceRange(ArgExprs.front()->getBeginLoc(),
6901  ArgExprs.back()->getEndLoc()));
6902  }
6903 
6904  return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6905  VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6906  }
6907  if (Fn->getType() == Context.PseudoObjectTy) {
6908  ExprResult result = CheckPlaceholderExpr(Fn);
6909  if (result.isInvalid()) return ExprError();
6910  Fn = result.get();
6911  }
6912 
6913  // Determine whether this is a dependent call inside a C++ template,
6914  // in which case we won't do any semantic analysis now.
6915  if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6916  if (ExecConfig) {
6918  cast<CallExpr>(ExecConfig), ArgExprs,
6920  RParenLoc, CurFPFeatureOverrides());
6921  } else {
6922 
6924  *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6925  Fn->getBeginLoc());
6926 
6927  return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6928  VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6929  }
6930  }
6931 
6932  // Determine whether this is a call to an object (C++ [over.call.object]).
6933  if (Fn->getType()->isRecordType())
6934  return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6935  RParenLoc);
6936 
6937  if (Fn->getType() == Context.UnknownAnyTy) {
6938  ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6939  if (result.isInvalid()) return ExprError();
6940  Fn = result.get();
6941  }
6942 
6943  if (Fn->getType() == Context.BoundMemberTy) {
6944  return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6945  RParenLoc, ExecConfig, IsExecConfig,
6946  AllowRecovery);
6947  }
6948  }
6949 
6950  // Check for overloaded calls. This can happen even in C due to extensions.
6951  if (Fn->getType() == Context.OverloadTy) {
6953 
6954  // We aren't supposed to apply this logic if there's an '&' involved.
6955  if (!find.HasFormOfMemberPointer) {
6956  if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6957  return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6958  VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6959  OverloadExpr *ovl = find.Expression;
6960  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6961  return BuildOverloadedCallExpr(
6962  Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6963  /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6964  return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6965  RParenLoc, ExecConfig, IsExecConfig,
6966  AllowRecovery);
6967  }
6968  }
6969 
6970  // If we're directly calling a function, get the appropriate declaration.
6971  if (Fn->getType() == Context.UnknownAnyTy) {
6972  ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6973  if (result.isInvalid()) return ExprError();
6974  Fn = result.get();
6975  }
6976 
6977  Expr *NakedFn = Fn->IgnoreParens();
6978 
6979  bool CallingNDeclIndirectly = false;
6980  NamedDecl *NDecl = nullptr;
6981  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6982  if (UnOp->getOpcode() == UO_AddrOf) {
6983  CallingNDeclIndirectly = true;
6984  NakedFn = UnOp->getSubExpr()->IgnoreParens();
6985  }
6986  }
6987 
6988  if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6989  NDecl = DRE->getDecl();
6990 
6991  FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6992  if (FDecl && FDecl->getBuiltinID()) {
6993  // Rewrite the function decl for this builtin by replacing parameters
6994  // with no explicit address space with the address space of the arguments
6995  // in ArgExprs.
6996  if ((FDecl =
6997  rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6998  NDecl = FDecl;
6999  Fn = DeclRefExpr::Create(
7000  Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
7001  SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
7002  nullptr, DRE->isNonOdrUse());
7003  }
7004  }
7005  } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
7006  NDecl = ME->getMemberDecl();
7007 
7008  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
7009  if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7010  FD, /*Complain=*/true, Fn->getBeginLoc()))
7011  return ExprError();
7012 
7013  checkDirectCallValidity(*this, Fn, FD, ArgExprs);
7014 
7015  // If this expression is a call to a builtin function in HIP device
7016  // compilation, allow a pointer-type argument to default address space to be
7017  // passed as a pointer-type parameter to a non-default address space.
7018  // If Arg is declared in the default address space and Param is declared
7019  // in a non-default address space, perform an implicit address space cast to
7020  // the parameter type.
7021  if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
7022  FD->getBuiltinID()) {
7023  for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
7024  ParmVarDecl *Param = FD->getParamDecl(Idx);
7025  if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7026  !ArgExprs[Idx]->getType()->isPointerType())
7027  continue;
7028 
7029  auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7030  auto ArgTy = ArgExprs[Idx]->getType();
7031  auto ArgPtTy = ArgTy->getPointeeType();
7032  auto ArgAS = ArgPtTy.getAddressSpace();
7033 
7034  // Add address space cast if target address spaces are different
7035  bool NeedImplicitASC =
7036  ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7037  ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7038  // or from specific AS which has target AS matching that of Param.
7040  if (!NeedImplicitASC)
7041  continue;
7042 
7043  // First, ensure that the Arg is an RValue.
7044  if (ArgExprs[Idx]->isGLValue()) {
7045  ArgExprs[Idx] = ImplicitCastExpr::Create(
7046  Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
7047  nullptr, VK_PRValue, FPOptionsOverride());
7048  }
7049 
7050  // Construct a new arg type with address space of Param
7051  Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7052  ArgPtQuals.setAddressSpace(ParamAS);
7053  auto NewArgPtTy =
7054  Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7055  auto NewArgTy =
7057  ArgTy.getQualifiers());
7058 
7059  // Finally perform an implicit address space cast
7060  ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7061  CK_AddressSpaceConversion)
7062  .get();
7063  }
7064  }
7065  }
7066 
7067  if (Context.isDependenceAllowed() &&
7068  (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7069  assert(!getLangOpts().CPlusPlus);
7070  assert((Fn->containsErrors() ||
7071  llvm::any_of(ArgExprs,
7072  [](clang::Expr *E) { return E->containsErrors(); })) &&
7073  "should only occur in error-recovery path.");
7074  QualType ReturnType =
7075  llvm::isa_and_nonnull<FunctionDecl>(NDecl)
7076  ? cast<FunctionDecl>(NDecl)->getCallResultType()
7077  : Context.DependentTy;
7078  return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
7079  Expr::getValueKindForType(ReturnType), RParenLoc,
7081  }
7082  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7083  ExecConfig, IsExecConfig);
7084 }
7085 
7086 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7087 // with the specified CallArgs
7089  MultiExprArg CallArgs) {
7090  StringRef Name = Context.BuiltinInfo.getName(Id);
7091  LookupResult R(*this, &Context.Idents.get(Name), Loc,
7093  LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7094 
7095  auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7096  assert(BuiltInDecl && "failed to find builtin declaration");
7097 
7098  ExprResult DeclRef =
7099  BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7100  assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7101 
7102  ExprResult Call =
7103  BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7104 
7105  assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7106  return Call.get();
7107 }
7108 
7109 /// Parse a __builtin_astype expression.
7110 ///
7111 /// __builtin_astype( value, dst type )
7112 ///
7114  SourceLocation BuiltinLoc,
7115  SourceLocation RParenLoc) {
7116  QualType DstTy = GetTypeFromParser(ParsedDestTy);
7117  return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7118 }
7119 
7120 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7122  SourceLocation BuiltinLoc,
7123  SourceLocation RParenLoc) {
7126  QualType SrcTy = E->getType();
7127  if (!SrcTy->isDependentType() &&
7128  Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7129  return ExprError(
7130  Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7131  << DestTy << SrcTy << E->getSourceRange());
7132  return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7133 }
7134 
7135 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7136 /// provided arguments.
7137 ///
7138 /// __builtin_convertvector( value, dst type )
7139 ///
7141  SourceLocation BuiltinLoc,
7142  SourceLocation RParenLoc) {
7143  TypeSourceInfo *TInfo;
7144  GetTypeFromParser(ParsedDestTy, &TInfo);
7145  return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7146 }
7147 
7148 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7149 /// i.e. an expression not of \p OverloadTy. The expression should
7150 /// unary-convert to an expression of function-pointer or
7151 /// block-pointer type.
7152 ///
7153 /// \param NDecl the declaration being called, if available
7155  SourceLocation LParenLoc,
7156  ArrayRef<Expr *> Args,
7157  SourceLocation RParenLoc, Expr *Config,
7158  bool IsExecConfig, ADLCallKind UsesADL) {
7159  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7160  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7161 
7162  // Functions with 'interrupt' attribute cannot be called directly.
7163  if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
7164  Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7165  return ExprError();
7166  }
7167 
7168  // Interrupt handlers don't save off the VFP regs automatically on ARM,
7169  // so there's some risk when calling out to non-interrupt handler functions
7170  // that the callee might not preserve them. This is easy to diagnose here,
7171  // but can be very challenging to debug.
7172  // Likewise, X86 interrupt handlers may only call routines with attribute
7173  // no_caller_saved_registers since there is no efficient way to
7174  // save and restore the non-GPR state.
7175  if (auto *Caller = getCurFunctionDecl()) {
7176  if (Caller->hasAttr<ARMInterruptAttr>()) {
7177  bool VFP = Context.getTargetInfo().hasFeature("vfp");
7178  if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
7179  Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
7180  if (FDecl)
7181  Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7182  }
7183  }
7184  if (Caller->hasAttr<AnyX86InterruptAttr>() &&
7185  ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
7186  Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
7187  if (FDecl)
7188  Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7189  }
7190  }
7191 
7192  // Promote the function operand.
7193  // We special-case function promotion here because we only allow promoting
7194  // builtin functions to function pointers in the callee of a call.
7195  ExprResult Result;
7196  QualType ResultTy;
7197  if (BuiltinID &&
7198  Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7199  // Extract the return type from the (builtin) function pointer type.
7200  // FIXME Several builtins still have setType in
7201  // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7202  // Builtins.def to ensure they are correct before removing setType calls.
7203  QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7204  Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7205  ResultTy = FDecl->getCallResultType();
7206  } else {
7207  Result = CallExprUnaryConversions(Fn);
7208  ResultTy = Context.BoolTy;
7209  }
7210  if (Result.isInvalid())
7211  return ExprError();
7212  Fn = Result.get();
7213 
7214  // Check for a valid function type, but only if it is not a builtin which
7215  // requires custom type checking. These will be handled by
7216  // CheckBuiltinFunctionCall below just after creation of the call expression.
7217  const FunctionType *FuncT = nullptr;
7218  if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7219  retry:
7220  if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7221  // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7222  // have type pointer to function".
7223  FuncT = PT->getPointeeType()->getAs<FunctionType>();
7224  if (!FuncT)
7225  return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7226  << Fn->getType() << Fn->getSourceRange());
7227  } else if (const BlockPointerType *BPT =
7228  Fn->getType()->getAs<BlockPointerType>()) {
7229  FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7230  } else {
7231  // Handle calls to expressions of unknown-any type.
7232  if (Fn->getType() == Context.UnknownAnyTy) {
7233  ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7234  if (rewrite.isInvalid())
7235  return ExprError();
7236  Fn = rewrite.get();
7237  goto retry;
7238  }
7239 
7240  return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7241  << Fn->getType() << Fn->getSourceRange());
7242  }
7243  }
7244 
7245  // Get the number of parameters in the function prototype, if any.
7246  // We will allocate space for max(Args.size(), NumParams) arguments
7247  // in the call expression.
7248  const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7249  unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7250 
7251  CallExpr *TheCall;
7252  if (Config) {
7253  assert(UsesADL == ADLCallKind::NotADL &&
7254  "CUDAKernelCallExpr should not use ADL");
7255  TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7256  Args, ResultTy, VK_PRValue, RParenLoc,
7257  CurFPFeatureOverrides(), NumParams);
7258  } else {
7259  TheCall =
7260  CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7261  CurFPFeatureOverrides(), NumParams, UsesADL);
7262  }
7263 
7264  if (!Context.isDependenceAllowed()) {
7265  // Forget about the nulled arguments since typo correction
7266  // do not handle them well.
7267  TheCall->shrinkNumArgs(Args.size());
7268  // C cannot always handle TypoExpr nodes in builtin calls and direct
7269  // function calls as their argument checking don't necessarily handle
7270  // dependent types properly, so make sure any TypoExprs have been
7271  // dealt with.
7272  ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7273  if (!Result.isUsable()) return ExprError();
7274  CallExpr *TheOldCall = TheCall;
7275  TheCall = dyn_cast<CallExpr>(Result.get());
7276  bool CorrectedTypos = TheCall != TheOldCall;
7277  if (!TheCall) return Result;
7278  Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7279 
7280  // A new call expression node was created if some typos were corrected.
7281  // However it may not have been constructed with enough storage. In this
7282  // case, rebuild the node with enough storage. The waste of space is
7283  // immaterial since this only happens when some typos were corrected.
7284  if (CorrectedTypos && Args.size() < NumParams) {
7285  if (Config)
7286  TheCall = CUDAKernelCallExpr::Create(
7287  Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7288  RParenLoc, CurFPFeatureOverrides(), NumParams);
7289  else
7290  TheCall =
7291  CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7292  CurFPFeatureOverrides(), NumParams, UsesADL);
7293  }
7294  // We can now handle the nulled arguments for the default arguments.
7295  TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7296  }
7297 
7298  // Bail out early if calling a builtin with custom type checking.
7299  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7300  return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7301 
7302  if (getLangOpts().CUDA) {
7303  if (Config) {
7304  // CUDA: Kernel calls must be to global functions
7305  if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7306  return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7307  << FDecl << Fn->getSourceRange());
7308 
7309  // CUDA: Kernel function must have 'void' return type
7310  if (!FuncT->getReturnType()->isVoidType() &&
7311  !FuncT->getReturnType()->getAs<AutoType>() &&
7313  return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7314  << Fn->getType() << Fn->getSourceRange());
7315  } else {
7316  // CUDA: Calls to global functions must be configured
7317  if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7318  return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7319  << FDecl << Fn->getSourceRange());
7320  }
7321  }
7322 
7323  // Check for a valid return type
7324  if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7325  FDecl))
7326  return ExprError();
7327 
7328  // We know the result type of the call, set it.
7329  TheCall->setType(FuncT->getCallResultType(Context));
7331 
7332  if (Proto) {
7333  if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7334  IsExecConfig))
7335  return ExprError();
7336  } else {
7337  assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7338 
7339  if (FDecl) {
7340  // Check if we have too few/too many template arguments, based
7341  // on our knowledge of the function definition.
7342  const FunctionDecl *Def = nullptr;
7343  if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7344  Proto = Def->getType()->getAs<FunctionProtoType>();
7345  if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7346  Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7347  << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7348  }
7349 
7350  // If the function we're calling isn't a function prototype, but we have
7351  // a function prototype from a prior declaratiom, use that prototype.
7352  if (!FDecl->hasPrototype())
7353  Proto = FDecl->getType()->getAs<FunctionProtoType>();
7354  }
7355 
7356  // If we still haven't found a prototype to use but there are arguments to
7357  // the call, diagnose this as calling a function without a prototype.
7358  // However, if we found a function declaration, check to see if
7359  // -Wdeprecated-non-prototype was disabled where the function was declared.
7360  // If so, we will silence the diagnostic here on the assumption that this
7361  // interface is intentional and the user knows what they're doing. We will
7362  // also silence the diagnostic if there is a function declaration but it
7363  // was implicitly defined (the user already gets diagnostics about the
7364  // creation of the implicit function declaration, so the additional warning
7365  // is not helpful).
7366  if (!Proto && !Args.empty() &&
7367  (!FDecl || (!FDecl->isImplicit() &&
7368  !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7369  FDecl->getLocation()))))
7370  Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7371  << (FDecl != nullptr) << FDecl;
7372 
7373  // Promote the arguments (C99 6.5.2.2p6).
7374  for (unsigned i = 0, e = Args.size(); i != e; i++) {
7375  Expr *Arg = Args[i];
7376 
7377  if (Proto && i < Proto->getNumParams()) {
7379  Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7380  ExprResult ArgE =
7381  PerformCopyInitialization(Entity, SourceLocation(), Arg);
7382  if (ArgE.isInvalid())
7383  return true;
7384 
7385  Arg = ArgE.getAs<Expr>();
7386 
7387  } else {
7389 
7390  if (ArgE.isInvalid())
7391  return true;
7392 
7393  Arg = ArgE.getAs<Expr>();
7394  }
7395 
7396  if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7397  diag::err_call_incomplete_argument, Arg))
7398  return ExprError();
7399 
7400  TheCall->setArg(i, Arg);
7401  }
7402  TheCall->computeDependence();
7403  }
7404 
7405  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7406  if (!Method->isStatic())
7407  return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7408  << Fn->getSourceRange());
7409 
7410  // Check for sentinels
7411  if (NDecl)
7412  DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7413 
7414  // Warn for unions passing across security boundary (CMSE).
7415  if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7416  for (unsigned i = 0, e = Args.size(); i != e; i++) {
7417  if (const auto *RT =
7418  dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7419  if (RT->getDecl()->isOrContainsUnion())
7420  Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7421  << 0 << i;
7422  }
7423  }
7424  }
7425 
7426  // Do special checking on direct calls to functions.
7427  if (FDecl) {
7428  if (CheckFunctionCall(FDecl, TheCall, Proto))
7429  return ExprError();
7430 
7431  checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7432 
7433  if (BuiltinID)
7434  return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7435  } else if (NDecl) {
7436  if (CheckPointerCall(NDecl, TheCall, Proto))
7437  return ExprError();
7438  } else {
7439  if (CheckOtherCall(TheCall, Proto))
7440  return ExprError();
7441  }
7442 
7443  return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7444 }
7445 
7446 ExprResult
7448  SourceLocation RParenLoc, Expr *InitExpr) {
7449  assert(Ty && "ActOnCompoundLiteral(): missing type");
7450  assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7451 
7452  TypeSourceInfo *TInfo;
7453  QualType literalType = GetTypeFromParser(Ty, &TInfo);
7454  if (!TInfo)
7455  TInfo = Context.getTrivialTypeSourceInfo(literalType);
7456 
7457  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7458 }
7459 
7460 ExprResult
7462  SourceLocation RParenLoc, Expr *LiteralExpr) {
7463  QualType literalType = TInfo->getType();
7464 
7465  if (literalType->isArrayType()) {
7467  LParenLoc, Context.getBaseElementType(literalType),
7468  diag::err_array_incomplete_or_sizeless_type,
7469  SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7470  return ExprError();
7471  if (literalType->isVariableArrayType()) {
7472  if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7473  diag::err_variable_object_no_init)) {
7474  return ExprError();
7475  }
7476  }
7477  } else if (!literalType->isDependentType() &&
7478  RequireCompleteType(LParenLoc, literalType,
7479  diag::err_typecheck_decl_incomplete_type,
7480  SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7481  return ExprError();
7482 
7483  InitializedEntity Entity
7487  SourceRange(LParenLoc, RParenLoc),
7488  /*InitList=*/true);
7489  InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7490  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7491  &literalType);
7492  if (Result.isInvalid())
7493  return ExprError();
7494  LiteralExpr = Result.get();
7495 
7496  bool isFileScope = !CurContext->isFunctionOrMethod();
7497 
7498  // In C, compound literals are l-values for some reason.
7499  // For GCC compatibility, in C++, file-scope array compound literals with
7500  // constant initializers are also l-values, and compound literals are
7501  // otherwise prvalues.
7502  //
7503  // (GCC also treats C++ list-initialized file-scope array prvalues with
7504  // constant initializers as l-values, but that's non-conforming, so we don't
7505  // follow it there.)
7506  //
7507  // FIXME: It would be better to handle the lvalue cases as materializing and
7508  // lifetime-extending a temporary object, but our materialized temporaries
7509  // representation only supports lifetime extension from a variable, not "out
7510  // of thin air".
7511  // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7512  // is bound to the result of applying array-to-pointer decay to the compound
7513  // literal.
7514  // FIXME: GCC supports compound literals of reference type, which should
7515  // obviously have a value kind derived from the kind of reference involved.
7516  ExprValueKind VK =
7517  (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7518  ? VK_PRValue
7519  : VK_LValue;
7520 
7521  if (isFileScope)
7522  if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7523  for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7524  Expr *Init = ILE->getInit(i);
7525  ILE->setInit(i, ConstantExpr::Create(Context, Init));
7526  }
7527 
7528  auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7529  VK, LiteralExpr, isFileScope);
7530  if (isFileScope) {
7531  if (!LiteralExpr->isTypeDependent() &&
7532  !LiteralExpr->isValueDependent() &&
7533  !literalType->isDependentType()) // C99 6.5.2.5p3
7534  if (CheckForConstantInitializer(LiteralExpr, literalType))
7535  return ExprError();
7536  } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7537  literalType.getAddressSpace() != LangAS::Default) {
7538  // Embedded-C extensions to C99 6.5.2.5:
7539  // "If the compound literal occurs inside the body of a function, the
7540  // type name shall not be qualified by an address-space qualifier."
7541  Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7542  << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7543  return ExprError();
7544  }
7545 
7546  if (!isFileScope && !getLangOpts().CPlusPlus) {
7547  // Compound literals that have automatic storage duration are destroyed at
7548  // the end of the scope in C; in C++, they're just temporaries.
7549 
7550  // Emit diagnostics if it is or contains a C union type that is non-trivial
7551  // to destruct.
7555 
7556  // Diagnose jumps that enter or exit the lifetime of the compound literal.
7557  if (literalType.isDestructedType()) {
7559  ExprCleanupObjects.push_back(E);
7561  }
7562  }
7563 
7566  checkNonTrivialCUnionInInitializer(E->getInitializer(),
7567  E->getInitializer()->getExprLoc());
7568 
7569  return MaybeBindToTemporary(E);
7570 }
7571 
7572 ExprResult
7574  SourceLocation RBraceLoc) {
7575  // Only produce each kind of designated initialization diagnostic once.
7576  SourceLocation FirstDesignator;
7577  bool DiagnosedArrayDesignator = false;
7578  bool DiagnosedNestedDesignator = false;
7579  bool DiagnosedMixedDesignator = false;
7580 
7581  // Check that any designated initializers are syntactically valid in the
7582  // current language mode.
7583  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7584  if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7585  if (FirstDesignator.isInvalid())
7586  FirstDesignator = DIE->getBeginLoc();
7587 
7588  if (!getLangOpts().CPlusPlus)
7589  break;
7590 
7591  if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7592  DiagnosedNestedDesignator = true;
7593  Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7594  << DIE->getDesignatorsSourceRange();
7595  }
7596 
7597  for (auto &Desig : DIE->designators()) {
7598  if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7599  DiagnosedArrayDesignator = true;
7600  Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7601  << Desig.getSourceRange();
7602  }
7603  }
7604 
7605  if (!DiagnosedMixedDesignator &&
7606  !isa<DesignatedInitExpr>(InitArgList[0])) {
7607  DiagnosedMixedDesignator = true;
7608  Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7609  << DIE->getSourceRange();
7610  Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7611  << InitArgList[0]->getSourceRange();
7612  }
7613  } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7614  isa<DesignatedInitExpr>(InitArgList[0])) {
7615  DiagnosedMixedDesignator = true;
7616  auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7617  Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7618  << DIE->getSourceRange();
7619  Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7620  << InitArgList[I]->getSourceRange();
7621  }
7622  }
7623 
7624  if (FirstDesignator.isValid()) {
7625  // Only diagnose designated initiaization as a C++20 extension if we didn't
7626  // already diagnose use of (non-C++20) C99 designator syntax.
7627  if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7628  !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7629  Diag(FirstDesignator, getLangOpts().CPlusPlus20
7630  ? diag::warn_cxx17_compat_designated_init
7631  : diag::ext_cxx_designated_init);
7632  } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7633  Diag(FirstDesignator, diag::ext_designated_init);
7634  }
7635  }
7636 
7637  return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7638 }
7639 
7640 ExprResult
7642  SourceLocation RBraceLoc) {
7643  // Semantic analysis for initializers is done by ActOnDeclarator() and
7644  // CheckInitializer() - it requires knowledge of the object being initialized.
7645 
7646  // Immediately handle non-overload placeholders. Overloads can be
7647  // resolved contextually, but everything else here can't.
7648  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7649  if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7650  ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7651 
7652  // Ignore failures; dropping the entire initializer list because
7653  // of one failure would be terrible for indexing/etc.
7654  if (result.isInvalid()) continue;
7655 
7656  InitArgList[I] = result.get();
7657  }
7658  }
7659 
7660  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7661  RBraceLoc);
7662  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7663  return E;
7664 }
7665 
7666 /// Do an explicit extend of the given block pointer if we're in ARC.
7668  assert(E.get()->getType()->isBlockPointerType());
7669  assert(E.get()->isPRValue());
7670 
7671  // Only do this in an r-value context.
7672  if (!getLangOpts().ObjCAutoRefCount) return;
7673 
7675  Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7676  /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7678 }
7679 
7680 /// Prepare a conversion of the given expression to an ObjC object
7681 /// pointer type.
7683  QualType type = E.get()->getType();
7684  if (type->isObjCObjectPointerType()) {
7685  return CK_BitCast;
7686  } else if (type->isBlockPointerType()) {
7688  return CK_BlockPointerToObjCPointerCast;
7689  } else {
7690  assert(type->isPointerType());
7691  return CK_CPointerToObjCPointerCast;
7692  }
7693 }
7694 
7695 /// Prepares for a scalar cast, performing all the necessary stages
7696 /// except the final cast and returning the kind required.
7698  // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7699  // Also, callers should have filtered out the invalid cases with
7700  // pointers. Everything else should be possible.
7701 
7702  QualType SrcTy = Src.get()->getType();
7703  if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7704  return CK_NoOp;
7705 
7706  switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7708  llvm_unreachable("member pointer type in C");
7709 
7710  case Type::STK_CPointer:
7713  switch (DestTy->getScalarTypeKind()) {
7714  case Type::STK_CPointer: {
7715  LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7716  LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7717  if (SrcAS != DestAS)
7718  return CK_AddressSpaceConversion;
7719  if (Context.hasCvrSimilarType(SrcTy, DestTy))
7720  return CK_NoOp;
7721  return CK_BitCast;
7722  }
7724  return (SrcKind == Type::STK_BlockPointer
7725  ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7727  if (SrcKind == Type::STK_ObjCObjectPointer)
7728  return CK_BitCast;
7729  if (SrcKind == Type::STK_CPointer)
7730  return CK_CPointerToObjCPointerCast;
7732  return CK_BlockPointerToObjCPointerCast;
7733  case Type::STK_Bool:
7734  return CK_PointerToBoolean;
7735  case Type::STK_Integral:
7736  return CK_PointerToIntegral;
7737  case Type::STK_Floating:
7741  case Type::STK_FixedPoint:
7742  llvm_unreachable("illegal cast from pointer");
7743  }
7744  llvm_unreachable("Should have returned before this");
7745 
7746  case Type::STK_FixedPoint:
7747  switch (DestTy->getScalarTypeKind()) {
7748  case Type::STK_FixedPoint:
7749  return CK_FixedPointCast;
7750  case Type::STK_Bool:
7751  return CK_FixedPointToBoolean;
7752  case Type::STK_Integral:
7753  return CK_FixedPointToIntegral;
7754  case Type::STK_Floating:
7755  return CK_FixedPointToFloating;
7758  Diag(Src.get()->getExprLoc(),
7759  diag::err_unimplemented_conversion_with_fixed_point_type)
7760  << DestTy;
7761  return CK_IntegralCast;
7762  case Type::STK_CPointer:
7766  llvm_unreachable("illegal cast to pointer type");
7767  }
7768  llvm_unreachable("Should have returned before this");
7769 
7770  case Type::STK_Bool: // casting from bool is like casting from an integer
7771  case Type::STK_Integral:
7772  switch (DestTy->getScalarTypeKind()) {
7773  case Type::STK_CPointer:
7776  if (Src.get()->isNullPointerConstant(Context,
7778  return CK_NullToPointer;
7779  return CK_IntegralToPointer;
7780  case Type::STK_Bool:
7781  return CK_IntegralToBoolean;
7782  case Type::STK_Integral:
7783  return CK_IntegralCast;
7784  case Type::STK_Floating:
7785  return CK_IntegralToFloating;
7787  Src = ImpCastExprToType(Src.get(),
7788  DestTy->castAs<ComplexType>()->getElementType(),
7789  CK_IntegralCast);
7790  return CK_IntegralRealToComplex;
7792  Src = ImpCastExprToType(Src.get(),
7793  DestTy->castAs<ComplexType>()->getElementType(),
7794  CK_IntegralToFloating);
7795  return CK_FloatingRealToComplex;
7797  llvm_unreachable("member pointer type in C");
7798  case Type::STK_FixedPoint:
7799  return CK_IntegralToFixedPoint;
7800  }
7801  llvm_unreachable("Should have returned before this");
7802 
7803  case Type::STK_Floating:
7804  switch (DestTy->getScalarTypeKind()) {
7805  case Type::STK_Floating:
7806  return CK_FloatingCast;
7807  case Type::STK_Bool:
7808  return CK_FloatingToBoolean;
7809  case Type::STK_Integral:
7810  return CK_FloatingToIntegral;
7812  Src = ImpCastExprToType(Src.get(),
7813  DestTy->castAs<ComplexType>()->getElementType(),
7814  CK_FloatingCast);
7815  return CK_FloatingRealToComplex;
7817  Src = ImpCastExprToType(Src.get(),
7818  DestTy->castAs<ComplexType>()->getElementType(),
7819  CK_FloatingToIntegral);
7820  return CK_IntegralRealToComplex;
7821  case Type::STK_CPointer:
7824  llvm_unreachable("valid float->pointer cast?");
7826  llvm_unreachable("member pointer type in C");
7827  case Type::STK_FixedPoint:
7828  return CK_FloatingToFixedPoint;
7829  }
7830  llvm_unreachable("Should have returned before this");
7831 
7833  switch (DestTy->getScalarTypeKind()) {
7835  return CK_FloatingComplexCast;
7837  return CK_FloatingComplexToIntegralComplex;
7838  case Type::STK_Floating: {
7839  QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7840  if (Context.hasSameType(ET, DestTy))
7841  return CK_FloatingComplexToReal;
7842  Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7843  return CK_FloatingCast;
7844  }
7845  case Type::STK_Bool:
7846  return CK_FloatingComplexToBoolean;
7847  case Type::STK_Integral:
7848  Src = ImpCastExprToType(Src.get(),
7849  SrcTy->castAs<ComplexType>()->getElementType(),
7850  CK_FloatingComplexToReal);
7851  return CK_FloatingToIntegral;
7852  case Type::STK_CPointer:
7855  llvm_unreachable("valid complex float->pointer cast?");
7857  llvm_unreachable("member pointer type in C");
7858  case Type::STK_FixedPoint:
7859  Diag(Src.get()->getExprLoc(),
7860  diag::err_unimplemented_conversion_with_fixed_point_type)
7861  << SrcTy;
7862  return CK_IntegralCast;
7863  }
7864  llvm_unreachable("Should have returned before this");
7865 
7867  switch (DestTy->getScalarTypeKind()) {
7869  return CK_IntegralComplexToFloatingComplex;
7871  return CK_IntegralComplexCast;
7872  case Type::STK_Integral: {
7873  QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7874  if (Context.hasSameType(ET, DestTy))
7875  return CK_IntegralComplexToReal;
7876  Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7877  return CK_IntegralCast;
7878  }
7879  case Type::STK_Bool:
7880  return CK_IntegralComplexToBoolean;
7881  case Type::STK_Floating:
7882  Src = ImpCastExprToType(Src.get(),
7883  SrcTy->castAs<ComplexType>()->getElementType(),
7884  CK_IntegralComplexToReal);
7885  return CK_IntegralToFloating;
7886  case Type::STK_CPointer:
7889  llvm_unreachable("valid complex int->pointer cast?");
7891  llvm_unreachable("member pointer type in C");
7892  case Type::STK_FixedPoint:
7893  Diag(Src.get()->getExprLoc(),
7894  diag::err_unimplemented_conversion_with_fixed_point_type)
7895  << SrcTy;
7896  return CK_IntegralCast;
7897  }
7898  llvm_unreachable("Should have returned before this");
7899  }
7900 
7901  llvm_unreachable("Unhandled scalar cast");
7902 }
7903 
7905  QualType &eltType) {
7906  // Vectors are simple.
7907  if (const VectorType *vecType = type->getAs<VectorType>()) {
7908  len = vecType->getNumElements();
7909  eltType = vecType->getElementType();
7910  assert(eltType->isScalarType());
7911  return true;
7912  }
7913 
7914  // We allow lax conversion to and from non-vector types, but only if
7915  // they're real types (i.e. non-complex, non-pointer scalar types).
7916  if (!type->isRealType()) return false;
7917 
7918  len = 1;
7919  eltType = type;
7920  return true;
7921 }
7922 
7923 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7924 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7925 /// allowed?
7926 ///
7927 /// This will also return false if the two given types do not make sense from
7928 /// the perspective of SVE bitcasts.
7930  assert(srcTy->isVectorType() || destTy->isVectorType());
7931 
7932  auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7933  if (!FirstType->isSizelessBuiltinType())
7934  return false;
7935 
7936  const auto *VecTy = SecondType->getAs<VectorType>();
7937  return VecTy &&
7939  };
7940 
7941  return ValidScalableConversion(srcTy, destTy) ||
7942  ValidScalableConversion(destTy, srcTy);
7943 }
7944 
7945 /// Are the two types matrix types and do they have the same dimensions i.e.
7946 /// do they have the same number of rows and the same number of columns?
7948  if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7949  return false;
7950 
7951  const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7952  const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7953 
7954  return matSrcType->getNumRows() == matDestType->getNumRows() &&
7955  matSrcType->getNumColumns() == matDestType->getNumColumns();
7956 }
7957 
7959  assert(DestTy->isVectorType() || SrcTy->isVectorType());
7960 
7961  uint64_t SrcLen, DestLen;
7962  QualType SrcEltTy, DestEltTy;
7963  if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7964  return false;
7965  if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7966  return false;
7967 
7968  // ASTContext::getTypeSize will return the size rounded up to a
7969  // power of 2, so instead of using that, we need to use the raw
7970  // element size multiplied by the element count.
7971  uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7972  uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7973 
7974  return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7975 }
7976 
7977 // This returns true if at least one of the types is an altivec vector.
7979  assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7980  "expected at least one type to be a vector here");
7981 
7982  bool IsSrcTyAltivec =
7983  SrcTy->isVectorType() && (SrcTy->castAs<VectorType>()->getVectorKind() ==
7985  bool IsDestTyAltivec = DestTy->isVectorType() &&
7986  (DestTy->castAs<VectorType>()->getVectorKind() ==
7988 
7989  return (IsSrcTyAltivec || IsDestTyAltivec);
7990 }
7991 
7992 // This returns true if both vectors have the same element type.
7994  assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7995  "expected at least one type to be a vector here");
7996 
7997  uint64_t SrcLen, DestLen;
7998  QualType SrcEltTy, DestEltTy;
7999  if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
8000  return false;
8001  if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
8002  return false;
8003 
8004  return (SrcEltTy == DestEltTy);
8005 }
8006 
8007 /// Are the two types lax-compatible vector types? That is, given
8008 /// that one of them is a vector, do they have equal storage sizes,
8009 /// where the storage size is the number of elements times the element
8010 /// size?
8011 ///
8012 /// This will also return false if either of the types is neither a
8013 /// vector nor a real type.
8015  assert(destTy->isVectorType() || srcTy->isVectorType());
8016 
8017  // Disallow lax conversions between scalars and ExtVectors (these
8018  // conversions are allowed for other vector types because common headers
8019  // depend on them). Most scalar OP ExtVector cases are handled by the
8020  // splat path anyway, which does what we want (convert, not bitcast).
8021  // What this rules out for ExtVectors is crazy things like char4*float.
8022  if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8023  if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8024 
8025  return areVectorTypesSameSize(srcTy, destTy);
8026 }
8027 
8028 /// Is this a legal conversion between two types, one of which is
8029 /// known to be a vector type?
8031  assert(destTy->isVectorType() || srcTy->isVectorType());
8032 
8033  switch (Context.getLangOpts().getLaxVectorConversions()) {
8035  return false;
8036 
8038  if (!srcTy->isIntegralOrEnumerationType()) {
8039  auto *Vec = srcTy->getAs<VectorType>();
8040  if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8041  return false;
8042  }
8043  if (!destTy->isIntegralOrEnumerationType()) {
8044  auto *Vec = destTy->getAs<VectorType>();
8045  if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8046  return false;
8047  }
8048  // OK, integer (vector) -> integer (vector) bitcast.
8049  break;
8050 
8052  break;
8053  }
8054 
8055  return areLaxCompatibleVectorTypes(srcTy, destTy);
8056 }
8057 
8059  CastKind &Kind) {
8060  if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8061  if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8062  return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8063  << DestTy << SrcTy << R;
8064  }
8065  } else if (SrcTy->isMatrixType()) {
8066  return Diag(R.getBegin(),
8067  diag::err_invalid_conversion_between_matrix_and_type)
8068  << SrcTy << DestTy << R;
8069  } else if (DestTy->isMatrixType()) {
8070  return Diag(R.getBegin(),
8071  diag::err_invalid_conversion_between_matrix_and_type)
8072  << DestTy << SrcTy << R;
8073  }
8074 
8075  Kind = CK_MatrixCast;
8076  return false;
8077 }
8078 
8080  CastKind &Kind) {
8081  assert(VectorTy->isVectorType() && "Not a vector type!");
8082 
8083  if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8084  if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8085  return Diag(R.getBegin(),
8086  Ty->isVectorType() ?
8087  diag::err_invalid_conversion_between_vectors :
8088  diag::err_invalid_conversion_between_vector_and_integer)
8089  << VectorTy << Ty << R;
8090  } else
8091  return Diag(R.getBegin(),
8092  diag::err_invalid_conversion_between_vector_and_scalar)
8093  << VectorTy << Ty << R;
8094 
8095  Kind = CK_BitCast;
8096  return false;
8097 }
8098 
8100  QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8101 
8102  if (DestElemTy == SplattedExpr->getType())
8103  return SplattedExpr;
8104 
8105  assert(DestElemTy->isFloatingType() ||
8106  DestElemTy->isIntegralOrEnumerationType());
8107 
8108  CastKind CK;
8109  if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8110  // OpenCL requires that we convert `true` boolean expressions to -1, but
8111  // only when splatting vectors.
8112  if (DestElemTy->isFloatingType()) {
8113  // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8114  // in two steps: boolean to signed integral, then to floating.
8115  ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8116  CK_BooleanToSignedIntegral);
8117  SplattedExpr = CastExprRes.get();
8118  CK = CK_IntegralToFloating;
8119  } else {
8120  CK = CK_BooleanToSignedIntegral;
8121  }
8122  } else {
8123  ExprResult CastExprRes = SplattedExpr;
8124  CK = PrepareScalarCast(CastExprRes, DestElemTy);
8125  if (CastExprRes.isInvalid())
8126  return ExprError();
8127  SplattedExpr = CastExprRes.get();
8128  }
8129  return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8130 }
8131 
8133  Expr *CastExpr, CastKind &Kind) {
8134  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8135 
8136  QualType SrcTy = CastExpr->getType();
8137 
8138  // If SrcTy is a VectorType, the total size must match to explicitly cast to
8139  // an ExtVectorType.
8140  // In OpenCL, casts between vectors of different types are not allowed.
8141  // (See OpenCL 6.2).
8142  if (SrcTy->isVectorType()) {
8143  if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8144  (getLangOpts().OpenCL &&
8145  !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
8146  Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8147  << DestTy << SrcTy << R;
8148  return ExprError();
8149  }
8150  Kind = CK_BitCast;
8151  return CastExpr;
8152  }
8153 
8154  // All non-pointer scalars can be cast to ExtVector type. The appropriate
8155  // conversion will take place first from scalar to elt type, and then
8156  // splat from elt type to vector.
8157  if (SrcTy->isPointerType())
8158  return Diag(R.getBegin(),
8159  diag::err_invalid_conversion_between_vector_and_scalar)
8160  << DestTy << SrcTy << R;
8161 
8162  Kind = CK_VectorSplat;
8163  return prepareVectorSplat(DestTy, CastExpr);
8164 }
8165 
8166 ExprResult
8168  Declarator &D, ParsedType &Ty,
8169  SourceLocation RParenLoc, Expr *CastExpr) {
8170  assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8171  "ActOnCastExpr(): missing type or expr");
8172 
8174  if (D.isInvalidType())
8175  return ExprError();
8176 
8177  if (getLangOpts().CPlusPlus) {
8178  // Check that there are no default arguments (C++ only).
8180  } else {
8181  // Make sure any TypoExprs have been dealt with.
8183  if (!Res.isUsable())
8184  return ExprError();
8185  CastExpr = Res.get();
8186  }
8187 
8189 
8190  QualType castType = castTInfo->getType();
8191  Ty = CreateParsedType(castType, castTInfo);
8192 
8193  bool isVectorLiteral = false;
8194 
8195  // Check for an altivec or OpenCL literal,
8196  // i.e. all the elements are integer constants.
8197  ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8198  ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8199  if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8200  && castType->isVectorType() && (PE || PLE)) {
8201  if (PLE && PLE->getNumExprs() == 0) {
8202  Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8203  return ExprError();
8204  }
8205  if (PE || PLE->getNumExprs() == 1) {
8206  Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8207  if (!E->isTypeDependent() && !E->getType()->isVectorType())
8208  isVectorLiteral = true;
8209  }
8210  else
8211  isVectorLiteral = true;
8212  }
8213 
8214  // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8215  // then handle it as such.
8216  if (isVectorLiteral)
8217  return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8218 
8219  // If the Expr being casted is a ParenListExpr, handle it specially.
8220  // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8221  // sequence of BinOp comma operators.
8222  if (isa<ParenListExpr>(CastExpr)) {
8224  if (Result.isInvalid()) return ExprError();
8225  CastExpr = Result.get();
8226  }
8227 
8228  if (getLangOpts().CPlusPlus && !castType->isVoidType())
8229  Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8230 
8231  CheckTollFreeBridgeCast(castType, CastExpr);
8232 
8234 
8236 
8237  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8238 }
8239 
8241  SourceLocation RParenLoc, Expr *E,
8242  TypeSourceInfo *TInfo) {
8243  assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8244  "Expected paren or paren list expression");
8245 
8246  Expr **exprs;
8247  unsigned numExprs;
8248  Expr *subExpr;
8249  SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8250  if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8251  LiteralLParenLoc = PE->getLParenLoc();
8252  LiteralRParenLoc = PE->getRParenLoc();
8253  exprs = PE->getExprs();
8254  numExprs = PE->getNumExprs();
8255  } else { // isa<ParenExpr> by assertion at function entrance
8256  LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8257  LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8258  subExpr = cast<ParenExpr>(E)->getSubExpr();
8259  exprs = &subExpr;
8260  numExprs = 1;
8261  }
8262 
8263  QualType Ty = TInfo->getType();
8264  assert(Ty->isVectorType() && "Expected vector type");
8265 
8266  SmallVector<Expr *, 8> initExprs;
8267  const VectorType *VTy = Ty->castAs<VectorType>();
8268  unsigned numElems = VTy->getNumElements();
8269 
8270  // '(...)' form of vector initialization in AltiVec: the number of
8271  // initializers must be one or must match the size of the vector.
8272  // If a single value is specified in the initializer then it will be
8273  // replicated to all the components of the vector
8275  VTy->getElementType()))
8276  return ExprError();
8277  if (ShouldSplatAltivecScalarInCast(VTy)) {
8278  // The number of initializers must be one or must match the size of the
8279  // vector. If a single value is specified in the initializer then it will
8280  // be replicated to all the components of the vector
8281  if (numExprs == 1) {
8282  QualType ElemTy = VTy->getElementType();
8284  if (Literal.isInvalid())
8285  return ExprError();
8286  Literal = ImpCastExprToType(Literal.get(), ElemTy,
8287  PrepareScalarCast(Literal, ElemTy));
8288  return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8289  }
8290  else if (numExprs < numElems) {
8291  Diag(E->getExprLoc(),
8292  diag::err_incorrect_number_of_vector_initializers);
8293  return ExprError();
8294  }
8295  else
8296  initExprs.append(exprs, exprs + numExprs);
8297  }
8298  else {
8299  // For OpenCL, when the number of initializers is a single value,
8300  // it will be replicated to all components of the vector.
8301  if (getLangOpts().OpenCL &&
8303  numExprs == 1) {
8304  QualType ElemTy = VTy->getElementType();
8306  if (Literal.isInvalid())
8307  return ExprError();
8308  Literal = ImpCastExprToType(Literal.get(), ElemTy,
8309  PrepareScalarCast(Literal, ElemTy));
8310  return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8311  }
8312 
8313  initExprs.append(exprs, exprs + numExprs);
8314  }
8315  // FIXME: This means that pretty-printing the final AST will produce curly
8316  // braces instead of the original commas.
8317  InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8318  initExprs, LiteralRParenLoc);
8319  initE->setType(Ty);
8320  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8321 }
8322 
8323 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8324 /// the ParenListExpr into a sequence of comma binary operators.
8325 ExprResult
8327  ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8328  if (!E)
8329  return OrigExpr;
8330 
8331  ExprResult Result(E->getExpr(0));
8332 
8333  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8334  Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8335  E->getExpr(i));
8336 
8337  if (Result.isInvalid()) return ExprError();
8338 
8339  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8340 }
8341 
8343  SourceLocation R,
8344  MultiExprArg Val) {
8345  return ParenListExpr::Create(Context, L, Val, R);
8346 }
8347 
8348 /// Emit a specialized diagnostic when one expression is a null pointer
8349 /// constant and the other is not a pointer. Returns true if a diagnostic is
8350 /// emitted.
8352  SourceLocation QuestionLoc) {
8353  Expr *NullExpr = LHSExpr;
8354  Expr *NonPointerExpr = RHSExpr;
8356  NullExpr->isNullPointerConstant(Context,
8358 
8359  if (NullKind == Expr::NPCK_NotNull) {
8360  NullExpr = RHSExpr;
8361  NonPointerExpr = LHSExpr;
8362  NullKind =
8363  NullExpr->isNullPointerConstant(Context,
8365  }
8366 
8367  if (NullKind == Expr::NPCK_NotNull)
8368  return false;
8369 
8370  if (NullKind == Expr::NPCK_ZeroExpression)
8371  return false;
8372 
8373  if (NullKind == Expr::NPCK_ZeroLiteral) {
8374  // In this case, check to make sure that we got here from a "NULL"
8375  // string in the source code.
8376  NullExpr = NullExpr->IgnoreParenImpCasts();
8377  SourceLocation loc = NullExpr->getExprLoc();
8378  if (!findMacroSpelling(loc, "NULL"))
8379  return false;
8380  }
8381 
8382  int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8383  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8384  << NonPointerExpr->getType() << DiagType
8385  << NonPointerExpr->getSourceRange();
8386  return true;
8387 }
8388 
8389 /// Return false if the condition expression is valid, true otherwise.
8390 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8391  QualType CondTy = Cond->getType();
8392 
8393  // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8394  if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8395  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8396  << CondTy << Cond->getSourceRange();
8397  return true;
8398  }
8399 
8400  // C99 6.5.15p2
8401  if (CondTy->isScalarType()) return false;
8402 
8403  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8404  << CondTy << Cond->getSourceRange();
8405  return true;
8406 }
8407 
8408 /// Return false if the NullExpr can be promoted to PointerTy,
8409 /// true otherwise.
8410 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8411  QualType PointerTy) {
8412  if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8413  !NullExpr.get()->isNullPointerConstant(S.Context,
8415  return true;
8416 
8417  NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8418  return false;
8419 }
8420 
8421 /// Checks compatibility between two pointers and return the resulting
8422 /// type.
8424  ExprResult &RHS,
8425  SourceLocation Loc) {
8426  QualType LHSTy = LHS.get()->getType();
8427  QualType RHSTy = RHS.get()->getType();
8428 
8429  if (S.Context.hasSameType(LHSTy, RHSTy)) {
8430  // Two identical pointers types are always compatible.
8431  return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8432  }
8433 
8434  QualType lhptee, rhptee;
8435 
8436  // Get the pointee types.
8437  bool IsBlockPointer = false;
8438  if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8439  lhptee = LHSBTy->getPointeeType();
8440  rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8441  IsBlockPointer = true;
8442  } else {
8443  lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8444  rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8445  }
8446 
8447  // C99 6.5.15p6: If both operands are pointers to compatible types or to
8448  // differently qualified versions of compatible types, the result type is
8449  // a pointer to an appropriately qualified version of the composite
8450  // type.
8451 
8452  // Only CVR-qualifiers exist in the standard, and the differently-qualified
8453  // clause doesn't make sense for our extensions. E.g. address space 2 should
8454  // be incompatible with address space 3: they may live on different devices or
8455  // anything.
8456  Qualifiers lhQual = lhptee.getQualifiers();
8457  Qualifiers rhQual = rhptee.getQualifiers();
8458 
8459  LangAS ResultAddrSpace = LangAS::Default;
8460  LangAS LAddrSpace = lhQual.getAddressSpace();
8461  LangAS RAddrSpace = rhQual.getAddressSpace();
8462 
8463  // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8464  // spaces is disallowed.
8465  if (lhQual.isAddressSpaceSupersetOf(rhQual))
8466  ResultAddrSpace = LAddrSpace;
8467  else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8468  ResultAddrSpace = RAddrSpace;
8469  else {
8470  S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8471  << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8472  << RHS.get()->getSourceRange();
8473  return QualType();
8474  }
8475 
8476  unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8477  auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8478  lhQual.removeCVRQualifiers();
8479  rhQual.removeCVRQualifiers();
8480 
8481  // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8482  // (C99 6.7.3) for address spaces. We assume that the check should behave in
8483  // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8484  // qual types are compatible iff
8485  // * corresponded types are compatible
8486  // * CVR qualifiers are equal
8487  // * address spaces are equal
8488  // Thus for conditional operator we merge CVR and address space unqualified
8489  // pointees and if there is a composite type we return a pointer to it with
8490  // merged qualifiers.
8491  LHSCastKind =
8492  LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8493  RHSCastKind =
8494  RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8495  lhQual.removeAddressSpace();
8496  rhQual.removeAddressSpace();
8497 
8498  lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8499  rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8500 
8501  QualType CompositeTy = S.Context.mergeTypes(
8502  lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8503  /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8504 
8505  if (CompositeTy.isNull()) {
8506  // In this situation, we assume void* type. No especially good
8507  // reason, but this is what gcc does, and we do have to pick
8508  // to get a consistent AST.
8509  QualType incompatTy;
8510  incompatTy = S.Context.getPointerType(
8511  S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8512  LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8513  RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8514 
8515  // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8516  // for casts between types with incompatible address space qualifiers.
8517  // For the following code the compiler produces casts between global and
8518  // local address spaces of the corresponded innermost pointees:
8519  // local int *global *a;
8520  // global int *global *b;
8521  // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8522  S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8523  << LHSTy << RHSTy << LHS.get()->getSourceRange()
8524  << RHS.get()->getSourceRange();
8525 
8526  return incompatTy;
8527  }
8528 
8529  // The pointer types are compatible.
8530  // In case of OpenCL ResultTy should have the address space qualifier
8531  // which is a superset of address spaces of both the 2nd and the 3rd
8532  // operands of the conditional operator.
8533  QualType ResultTy = [&, ResultAddrSpace]() {
8534  if (S.getLangOpts().OpenCL) {
8535  Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8536  CompositeQuals.setAddressSpace(ResultAddrSpace);
8537  return S.Context
8538  .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8539  .withCVRQualifiers(MergedCVRQual);
8540  }
8541  return CompositeTy.withCVRQualifiers(MergedCVRQual);
8542  }();
8543  if (IsBlockPointer)
8544  ResultTy = S.Context.getBlockPointerType(ResultTy);
8545  else
8546  ResultTy = S.Context.getPointerType(ResultTy);
8547 
8548  LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8549  RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8550  return ResultTy;
8551 }
8552 
8553 /// Return the resulting type when the operands are both block pointers.
8555  ExprResult &LHS,
8556  ExprResult &RHS,
8557  SourceLocation Loc) {
8558  QualType LHSTy = LHS.get()->getType();
8559  QualType RHSTy = RHS.get()->getType();
8560 
8561  if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8562  if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8563  QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8564  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8565  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8566  return destType;
8567  }
8568  S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8569  << LHSTy << RHSTy << LHS.get()->getSourceRange()
8570  << RHS.get()->getSourceRange();
8571  return QualType();
8572  }
8573 
8574  // We have 2 block pointer types.
8575  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8576 }
8577 
8578 /// Return the resulting type when the operands are both pointers.
8579 static QualType
8581  ExprResult &RHS,
8582  SourceLocation Loc) {
8583  // get the pointer types
8584  QualType LHSTy = LHS.get()->getType();
8585  QualType RHSTy = RHS.get()->getType();
8586 
8587  // get the "pointed to" types
8588  QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8589  QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8590 
8591  // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8592  if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8593  // Figure out necessary qualifiers (C99 6.5.15p6)
8594  QualType destPointee
8595  = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8596  QualType destType = S.Context.getPointerType(destPointee);
8597  // Add qualifiers if necessary.
8598  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8599  // Promote to void*.
8600  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8601  return destType;
8602  }
8603  if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8604  QualType destPointee
8605  = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8606  QualType destType = S.Context.getPointerType(destPointee);
8607  // Add qualifiers if necessary.
8608  RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8609  // Promote to void*.
8610  LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8611  return destType;
8612  }
8613 
8614  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8615 }
8616 
8617 /// Return false if the first expression is not an integer and the second
8618 /// expression is not a pointer, true otherwise.
8620  Expr* PointerExpr, SourceLocation Loc,
8621  bool IsIntFirstExpr) {
8622  if (!PointerExpr->getType()->isPointerType() ||
8623  !Int.get()->getType()->isIntegerType())
8624  return false;
8625 
8626  Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8627  Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8628 
8629  S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8630  << Expr1->getType() << Expr2->getType()
8631  << Expr1->getSourceRange() << Expr2->getSourceRange();
8632  Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8633  CK_IntegralToPointer);
8634  return true;
8635 }
8636 
8637 /// Simple conversion between integer and floating point types.
8638 ///
8639 /// Used when handling the OpenCL conditional operator where the
8640 /// condition is a vector while the other operands are scalar.
8641 ///
8642 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8643 /// types are either integer or floating type. Between the two
8644 /// operands, the type with the higher rank is defined as the "result
8645 /// type". The other operand needs to be promoted to the same type. No
8646 /// other type promotion is allowed. We cannot use
8647 /// UsualArithmeticConversions() for this purpose, since it always
8648 /// promotes promotable types.
8650  ExprResult &RHS,
8651  SourceLocation QuestionLoc) {
8653  if (LHS.isInvalid())
8654  return QualType();
8656  if (RHS.isInvalid())
8657  return QualType();
8658 
8659  // For conversion purposes, we ignore any qualifiers.
8660  // For example, "const float" and "float" are equivalent.
8661  QualType LHSType =
8663  QualType RHSType =
8665 
8666  if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8667  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8668  << LHSType << LHS.get()->getSourceRange();
8669  return QualType();
8670  }
8671 
8672  if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8673  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8674  << RHSType << RHS.get()->getSourceRange();
8675  return QualType();
8676  }
8677 
8678  // If both types are identical, no conversion is needed.
8679  if (LHSType == RHSType)
8680  return LHSType;
8681 
8682  // Now handle "real" floating types (i.e. float, double, long double).
8683  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8684  return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8685  /*IsCompAssign = */ false);
8686 
8687  // Finally, we have two differing integer types.
8688  return handleIntegerConversion<doIntegralCast, doIntegralCast>
8689  (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8690 }
8691 
8692 /// Convert scalar operands to a vector that matches the
8693 /// condition in length.
8694 ///
8695 /// Used when handling the OpenCL conditional operator where the
8696 /// condition is a vector while the other operands are scalar.
8697 ///
8698 /// We first compute the "result type" for the scalar operands
8699 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8700 /// into a vector of that type where the length matches the condition
8701 /// vector type. s6.11.6 requires that the element types of the result
8702 /// and the condition must have the same number of bits.
8703 static QualType
8705  QualType CondTy, SourceLocation QuestionLoc) {
8706  QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8707  if (ResTy.isNull()) return QualType();
8708 
8709  const VectorType *CV = CondTy->getAs<VectorType>();
8710  assert(CV);
8711 
8712  // Determine the vector result type
8713  unsigned NumElements = CV->getNumElements();
8714  QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8715 
8716  // Ensure that all types have the same number of bits
8717  if (S.Context.getTypeSize(CV->getElementType())
8718  != S.Context.getTypeSize(ResTy)) {
8719  // Since VectorTy is created internally, it does not pretty print
8720  // with an OpenCL name. Instead, we just print a description.
8721  std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8722  SmallString<64> Str;
8723  llvm::raw_svector_ostream OS(Str);
8724  OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8725  S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8726  << CondTy << OS.str();
8727  return QualType();
8728  }
8729 
8730  // Convert operands to the vector result type
8731  LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8732  RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8733 
8734  return VectorTy;
8735 }
8736 
8737 /// Return false if this is a valid OpenCL condition vector
8738 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8739  SourceLocation QuestionLoc) {
8740  // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8741  // integral type.
8742  const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8743  assert(CondTy);
8744  QualType EleTy = CondTy->getElementType();
8745  if (EleTy->isIntegerType()) return false;
8746 
8747  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8748  << Cond->getType() << Cond->getSourceRange();
8749  return true;
8750 }
8751 
8752 /// Return false if the vector condition type and the vector
8753 /// result type are compatible.
8754 ///
8755 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8756 /// number of elements, and their element types have the same number
8757 /// of bits.
8758 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8759  SourceLocation QuestionLoc) {
8760  const VectorType *CV = CondTy->getAs<VectorType>();
8761  const VectorType *RV = VecResTy->getAs<VectorType>();
8762  assert(CV && RV);
8763 
8764  if (CV->getNumElements() != RV->getNumElements()) {
8765  S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8766  << CondTy << VecResTy;
8767  return true;
8768  }
8769 
8770  QualType CVE = CV->getElementType();
8771  QualType RVE = RV->getElementType();
8772 
8773  if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8774  S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8775  << CondTy << VecResTy;
8776  return true;
8777  }
8778 
8779  return false;
8780 }
8781 
8782 /// Return the resulting type for the conditional operator in
8783 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
8784 /// s6.3.i) when the condition is a vector type.
8785 static QualType
8787  ExprResult &LHS, ExprResult &RHS,
8788  SourceLocation QuestionLoc) {
8789  Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8790  if (Cond.isInvalid())
8791  return QualType();
8792  QualType CondTy = Cond.get()->getType();
8793 
8794  if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8795  return QualType();
8796 
8797  // If either operand is a vector then find the vector type of the
8798  // result as specified in OpenCL v1.1 s6.3.i.
8799  if (LHS.get()->getType()->isVectorType() ||
8800  RHS.get()->getType()->isVectorType()) {
8801  bool IsBoolVecLang =
8802  !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8803  QualType VecResTy =
8804  S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8805  /*isCompAssign*/ false,
8806  /*AllowBothBool*/ true,
8807  /*AllowBoolConversions*/ false,
8808  /*AllowBooleanOperation*/ IsBoolVecLang,
8809  /*ReportInvalid*/ true);
8810  if (VecResTy.isNull())
8811  return QualType();
8812  // The result type must match the condition type as specified in
8813  // OpenCL v1.1 s6.11.6.
8814  if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8815  return QualType();
8816  return VecResTy;
8817  }
8818 
8819  // Both operands are scalar.
8820  return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8821 }
8822 
8823 /// Return true if the Expr is block type
8824 static bool checkBlockType(Sema &S, const Expr *E) {
8825  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8826  QualType Ty = CE->getCallee()->getType();
8827  if (Ty->isBlockPointerType()) {
8828  S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8829  return true;
8830  }
8831  }
8832  return false;
8833 }
8834 
8835 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8836 /// In that case, LHS = cond.
8837 /// C99 6.5.15
8839  ExprResult &RHS, ExprValueKind &VK,
8840  ExprObjectKind &OK,
8841  SourceLocation QuestionLoc) {
8842 
8843  ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8844  if (!LHSResult.isUsable()) return QualType();
8845  LHS = LHSResult;
8846 
8847  ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8848  if (!RHSResult.isUsable()) return QualType();
8849  RHS = RHSResult;
8850 
8851  // C++ is sufficiently different to merit its own checker.
8852  if (getLangOpts().CPlusPlus)
8853  return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8854 
8855  VK = VK_PRValue;
8856  OK = OK_Ordinary;
8857 
8858  if (Context.isDependenceAllowed() &&
8859  (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8860  RHS.get()->isTypeDependent())) {
8861  assert(!getLangOpts().CPlusPlus);
8862  assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8863  RHS.get()->containsErrors()) &&
8864  "should only occur in error-recovery path.");
8865  return Context.DependentTy;
8866  }
8867 
8868  // The OpenCL operator with a vector condition is sufficiently
8869  // different to merit its own checker.
8870  if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8871  Cond.get()->getType()->isExtVectorType())
8872  return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8873 
8874  // First, check the condition.
8875  Cond = UsualUnaryConversions(Cond.get());
8876  if (Cond.isInvalid())
8877  return QualType();
8878  if (checkCondition(*this, Cond.get(), QuestionLoc))
8879  return QualType();
8880 
8881  // Now check the two expressions.
8882  if (LHS.get()->getType()->isVectorType() ||
8883  RHS.get()->getType()->isVectorType())
8884  return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8885  /*AllowBothBool*/ true,
8886  /*AllowBoolConversions*/ false,
8887  /*AllowBooleanOperation*/ false,
8888  /*ReportInvalid*/ true);
8889 
8890  QualType ResTy =
8891  UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8892  if (LHS.isInvalid() || RHS.isInvalid())
8893  return QualType();
8894 
8895  QualType LHSTy = LHS.get()->getType();
8896  QualType RHSTy = RHS.get()->getType();
8897 
8898  // Diagnose attempts to convert between __ibm128, __float128 and long double
8899  // where such conversions currently can't be handled.
8900  if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8901  Diag(QuestionLoc,
8902  diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8903  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8904  return QualType();
8905  }
8906 
8907  // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8908  // selection operator (?:).
8909  if (getLangOpts().OpenCL &&
8910  ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8911  return QualType();
8912  }
8913 
8914  // If both operands have arithmetic type, do the usual arithmetic conversions
8915  // to find a common type: C99 6.5.15p3,5.
8916  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8917  // Disallow invalid arithmetic conversions, such as those between bit-
8918  // precise integers types of different sizes, or between a bit-precise
8919  // integer and another type.
8920  if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8921  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8922  << LHSTy << RHSTy << LHS.get()->getSourceRange()
8923  << RHS.get()->getSourceRange();
8924  return QualType();
8925  }
8926 
8927  LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8928  RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8929 
8930  return ResTy;
8931  }
8932 
8933  // And if they're both bfloat (which isn't arithmetic), that's fine too.
8934  if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8935  return Context.getCommonSugaredType(LHSTy, RHSTy);
8936  }
8937 
8938  // If both operands are the same structure or union type, the result is that
8939  // type.
8940  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8941  if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8942  if (LHSRT->getDecl() == RHSRT->getDecl())
8943  // "If both the operands have structure or union type, the result has
8944  // that type." This implies that CV qualifiers are dropped.
8946  RHSTy.getUnqualifiedType());
8947  // FIXME: Type of conditional expression must be complete in C mode.
8948  }
8949 
8950  // C99 6.5.15p5: "If both operands have void type, the result has void type."
8951  // The following || allows only one side to be void (a GCC-ism).
8952  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8953  QualType ResTy;
8954  if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8955  ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8956  } else if (RHSTy->isVoidType()) {
8957  ResTy = RHSTy;
8958  Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8959  << RHS.get()->getSourceRange();
8960  } else {
8961  ResTy = LHSTy;
8962  Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8963  << LHS.get()->getSourceRange();
8964  }
8965  LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8966  RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8967  return ResTy;
8968  }
8969 
8970  // C2x 6.5.15p7:
8971  // ... if both the second and third operands have nullptr_t type, the
8972  // result also has that type.
8973  if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8974  return ResTy;
8975 
8976  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8977  // the type of the other operand."
8978  if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8979  if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8980 
8981  // All objective-c pointer type analysis is done here.
8982  QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8983  QuestionLoc);
8984  if (LHS.isInvalid() || RHS.isInvalid())
8985  return QualType();
8986  if (!compositeType.isNull())
8987  return compositeType;
8988 
8989 
8990  // Handle block pointer types.
8991  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8992  return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8993  QuestionLoc);
8994 
8995  // Check constraints for C object pointers types (C99 6.5.15p3,6).
8996  if (LHSTy->isPointerType() && RHSTy->isPointerType())
8997  return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8998  QuestionLoc);
8999 
9000  // GCC compatibility: soften pointer/integer mismatch. Note that
9001  // null pointers have been filtered out by this point.
9002  if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9003  /*IsIntFirstExpr=*/true))
9004  return RHSTy;
9005  if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9006  /*IsIntFirstExpr=*/false))
9007  return LHSTy;
9008 
9009  // Allow ?: operations in which both operands have the same
9010  // built-in sizeless type.
9011  if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
9012  return Context.getCommonSugaredType(LHSTy, RHSTy);
9013 
9014  // Emit a better diagnostic if one of the expressions is a null pointer
9015  // constant and the other is not a pointer type. In this case, the user most
9016  // likely forgot to take the address of the other expression.
9017  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9018  return QualType();
9019 
9020  // Otherwise, the operands are not compatible.
9021  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9022  << LHSTy << RHSTy << LHS.get()->getSourceRange()
9023  << RHS.get()->getSourceRange();
9024  return QualType();
9025 }
9026 
9027 /// FindCompositeObjCPointerType - Helper method to find composite type of
9028 /// two objective-c pointer types of the two input expressions.
9030  SourceLocation QuestionLoc) {
9031  QualType LHSTy = LHS.get()->getType();
9032  QualType RHSTy = RHS.get()->getType();
9033 
9034  // Handle things like Class and struct objc_class*. Here we case the result
9035  // to the pseudo-builtin, because that will be implicitly cast back to the
9036  // redefinition type if an attempt is made to access its fields.
9037  if (LHSTy->isObjCClassType() &&
9039  RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9040  return LHSTy;
9041  }
9042  if (RHSTy->isObjCClassType() &&
9044  LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9045  return RHSTy;
9046  }
9047  // And the same for struct objc_object* / id
9048  if (LHSTy->isObjCIdType() &&
9050  RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9051  return LHSTy;
9052  }
9053  if (RHSTy->isObjCIdType() &&
9055  LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9056  return RHSTy;
9057  }
9058  // And the same for struct objc_selector* / SEL
9059  if (Context.isObjCSelType(LHSTy) &&
9061  RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
9062  return LHSTy;
9063  }
9064  if (Context.isObjCSelType(RHSTy) &&
9066  LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
9067  return RHSTy;
9068  }
9069  // Check constraints for Objective-C object pointers types.
9070  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
9071 
9072  if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
9073  // Two identical object pointer types are always compatible.
9074  return LHSTy;
9075  }
9076  const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
9077  const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
9078  QualType compositeType = LHSTy;
9079 
9080  // If both operands are interfaces and either operand can be
9081  // assigned to the other, use that type as the composite
9082  // type. This allows
9083  // xxx ? (A*) a : (B*) b
9084  // where B is a subclass of A.
9085  //
9086  // Additionally, as for assignment, if either type is 'id'
9087  // allow silent coercion. Finally, if the types are
9088  // incompatible then make sure to use 'id' as the composite
9089  // type so the result is acceptable for sending messages to.
9090 
9091  // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
9092  // It could return the composite type.
9093  if (!(compositeType =
9094  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
9095  // Nothing more to do.
9096  } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
9097  compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
9098  } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
9099  compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
9100  } else if ((LHSOPT->isObjCQualifiedIdType() ||
9101  RHSOPT->isObjCQualifiedIdType()) &&
9103  true)) {
9104  // Need to handle "id<xx>" explicitly.
9105  // GCC allows qualified id and any Objective-C type to devolve to
9106  // id. Currently localizing to here until clear this should be
9107  // part of ObjCQualifiedIdTypesAreCompatible.
9108  compositeType = Context.getObjCIdType();
9109  } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
9110  compositeType = Context.getObjCIdType();
9111  } else {
9112  Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
9113  << LHSTy << RHSTy
9114  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9115  QualType incompatTy = Context.getObjCIdType();
9116  LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
9117  RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
9118  return incompatTy;
9119  }
9120  // The object pointer types are compatible.
9121  LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
9122  RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
9123  return compositeType;
9124  }
9125  // Check Objective-C object pointer types and 'void *'
9126  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
9127  if (getLangOpts().ObjCAutoRefCount) {
9128  // ARC forbids the implicit conversion of object pointers to 'void *',
9129  // so these types are not compatible.
9130  Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9131  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9132  LHS = RHS = true;
9133  return QualType();
9134  }
9135  QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
9136  QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9137  QualType destPointee
9138  = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
9139  QualType destType = Context.getPointerType(destPointee);
9140  // Add qualifiers if necessary.
9141  LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
9142  // Promote to void*.
9143  RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
9144  return destType;
9145  }
9146  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
9147  if (getLangOpts().ObjCAutoRefCount) {
9148  // ARC forbids the implicit conversion of object pointers to 'void *',
9149  // so these types are not compatible.
9150  Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9151  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9152  LHS = RHS = true;
9153  return QualType();
9154  }
9155  QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9156  QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
9157  QualType destPointee
9158  = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
9159  QualType destType = Context.getPointerType(destPointee);
9160  // Add qualifiers if necessary.
9161  RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
9162  // Promote to void*.
9163  LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
9164  return destType;
9165  }
9166  return QualType();
9167 }
9168 
9169 /// SuggestParentheses - Emit a note with a fixit hint that wraps
9170 /// ParenRange in parentheses.
9171 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9172  const PartialDiagnostic &Note,
9173  SourceRange ParenRange) {
9174  SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9175  if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9176  EndLoc.isValid()) {
9177  Self.Diag(Loc, Note)
9178  << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9179  << FixItHint::CreateInsertion(EndLoc, ")");
9180  } else {
9181  // We can't display the parentheses, so just show the bare note.
9182  Self.Diag(Loc, Note) << ParenRange;
9183  }
9184 }
9185 
9187  return BinaryOperator::isAdditiveOp(Opc) ||
9189  BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9190  // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9191  // not any of the logical operators. Bitwise-xor is commonly used as a
9192  // logical-xor because there is no logical-xor operator. The logical
9193  // operators, including uses of xor, have a high false positive rate for
9194  // precedence warnings.
9195 }
9196 
9197 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9198 /// expression, either using a built-in or overloaded operator,
9199 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9200 /// expression.
9202  Expr **RHSExprs) {
9203  // Don't strip parenthesis: we should not warn if E is in parenthesis.
9204  E = E->IgnoreImpCasts();
9206  E = E->IgnoreImpCasts();
9207  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9208  E = MTE->getSubExpr();
9209  E = E->IgnoreImpCasts();
9210  }
9211 
9212  // Built-in binary operator.
9213  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
9214  if (IsArithmeticOp(OP->getOpcode())) {
9215  *Opcode = OP->getOpcode();
9216  *RHSExprs = OP->getRHS();
9217  return true;
9218  }
9219  }
9220 
9221  // Overloaded operator.
9222  if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9223  if (Call->getNumArgs() != 2)
9224  return false;
9225 
9226  // Make sure this is really a binary operator that is safe to pass into
9227  // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9228  OverloadedOperatorKind OO = Call->getOperator();
9229  if (OO < OO_Plus || OO > OO_Arrow ||
9230  OO == OO_PlusPlus || OO == OO_MinusMinus)
9231  return false;
9232 
9234  if (IsArithmeticOp(OpKind)) {
9235  *Opcode = OpKind;
9236  *RHSExprs = Call->getArg(1);
9237  return true;
9238  }
9239  }
9240 
9241  return false;
9242 }
9243 
9244 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9245 /// or is a logical expression such as (x==y) which has int type, but is
9246 /// commonly interpreted as boolean.
9247 static bool ExprLooksBoolean(Expr *E) {
9248  E = E->IgnoreParenImpCasts();
9249 
9250  if (E->getType()->isBooleanType())
9251  return true;
9252  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
9253  return OP->isComparisonOp() || OP->isLogicalOp();
9254  if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
9255  return OP->getOpcode() == UO_LNot;
9256  if (E->getType()->isPointerType())
9257  return true;
9258  // FIXME: What about overloaded operator calls returning "unspecified boolean
9259  // type"s (commonly pointer-to-members)?
9260 
9261  return false;
9262 }
9263 
9264 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9265 /// and binary operator are mixed in a way that suggests the programmer assumed
9266 /// the conditional operator has higher precedence, for example:
9267 /// "int x = a + someBinaryCondition ? 1 : 2".
9269  SourceLocation OpLoc,
9270  Expr *Condition,
9271  Expr *LHSExpr,
9272  Expr *RHSExpr) {
9273  BinaryOperatorKind CondOpcode;
9274  Expr *CondRHS;
9275 
9276  if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9277  return;
9278  if (!ExprLooksBoolean(CondRHS))
9279  return;
9280 
9281  // The condition is an arithmetic binary expression, with a right-
9282  // hand side that looks boolean, so warn.
9283 
9284  unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9285  ? diag::warn_precedence_bitwise_conditional
9286  : diag::warn_precedence_conditional;
9287 
9288  Self.Diag(OpLoc, DiagID)
9289  << Condition->getSourceRange()
9290  << BinaryOperator::getOpcodeStr(CondOpcode);
9291 
9293  Self, OpLoc,
9294  Self.PDiag(diag::note_precedence_silence)
9295  << BinaryOperator::getOpcodeStr(CondOpcode),
9296  SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9297 
9298  SuggestParentheses(Self, OpLoc,
9299  Self.PDiag(diag::note_precedence_conditional_first),
9300  SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9301 }
9302 
9303 /// Compute the nullability of a conditional expression.
9305  QualType LHSTy, QualType RHSTy,
9306  ASTContext &Ctx) {
9307  if (!ResTy->isAnyPointerType())
9308  return ResTy;
9309 
9310  auto GetNullability = [](QualType Ty) {
9311  std::optional<NullabilityKind> Kind = Ty->getNullability();
9312  if (Kind) {
9313  // For our purposes, treat _Nullable_result as _Nullable.
9316  return *Kind;
9317  }
9319  };
9320 
9321  auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9322  NullabilityKind MergedKind;
9323 
9324  // Compute nullability of a binary conditional expression.
9325  if (IsBin) {
9326  if (LHSKind == NullabilityKind::NonNull)
9327  MergedKind = NullabilityKind::NonNull;
9328  else
9329  MergedKind = RHSKind;
9330  // Compute nullability of a normal conditional expression.
9331  } else {
9332  if (LHSKind == NullabilityKind::Nullable ||
9333  RHSKind == NullabilityKind::Nullable)
9334  MergedKind = NullabilityKind::Nullable;
9335  else if (LHSKind == NullabilityKind::NonNull)
9336  MergedKind = RHSKind;
9337  else if (RHSKind == NullabilityKind::NonNull)
9338  MergedKind = LHSKind;
9339  else
9340  MergedKind = NullabilityKind::Unspecified;
9341  }
9342 
9343  // Return if ResTy already has the correct nullability.
9344  if (GetNullability(ResTy) == MergedKind)
9345  return ResTy;
9346 
9347  // Strip all nullability from ResTy.
9348  while (ResTy->getNullability())
9349  ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9350 
9351  // Create a new AttributedType with the new nullability kind.
9352  auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9353  return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9354 }
9355 
9356 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9357 /// in the case of a the GNU conditional expr extension.
9359  SourceLocation ColonLoc,
9360  Expr *CondExpr, Expr *LHSExpr,
9361  Expr *RHSExpr) {
9362  if (!Context.isDependenceAllowed()) {
9363  // C cannot handle TypoExpr nodes in the condition because it
9364  // doesn't handle dependent types properly, so make sure any TypoExprs have
9365  // been dealt with before checking the operands.
9366  ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9367  ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9368  ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9369 
9370  if (!CondResult.isUsable())
9371  return ExprError();
9372 
9373  if (LHSExpr) {
9374  if (!LHSResult.isUsable())
9375  return ExprError();
9376  }
9377 
9378  if (!RHSResult.isUsable())
9379  return ExprError();
9380 
9381  CondExpr = CondResult.get();
9382  LHSExpr = LHSResult.get();
9383  RHSExpr = RHSResult.get();
9384  }
9385 
9386  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9387  // was the condition.
9388  OpaqueValueExpr *opaqueValue = nullptr;
9389  Expr *commonExpr = nullptr;
9390  if (!LHSExpr) {
9391  commonExpr = CondExpr;
9392  // Lower out placeholder types first. This is important so that we don't
9393  // try to capture a placeholder. This happens in few cases in C++; such
9394  // as Objective-C++'s dictionary subscripting syntax.
9395  if (commonExpr->hasPlaceholderType()) {
9396  ExprResult result = CheckPlaceholderExpr(commonExpr);
9397  if (!result.isUsable()) return ExprError();
9398  commonExpr = result.get();
9399  }
9400  // We usually want to apply unary conversions *before* saving, except
9401  // in the special case of a C++ l-value conditional.
9402  if (!(getLangOpts().CPlusPlus
9403  && !commonExpr->isTypeDependent()
9404  && commonExpr->getValueKind() == RHSExpr->getValueKind()
9405  && commonExpr->isGLValue()
9406  && commonExpr->isOrdinaryOrBitFieldObject()
9407  && RHSExpr->isOrdinaryOrBitFieldObject()
9408  && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9409  ExprResult commonRes = UsualUnaryConversions(commonExpr);
9410  if (commonRes.isInvalid())
9411  return ExprError();
9412  commonExpr = commonRes.get();
9413  }
9414 
9415  // If the common expression is a class or array prvalue, materialize it
9416  // so that we can safely refer to it multiple times.
9417  if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9418  commonExpr->getType()->isArrayType())) {
9419  ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9420  if (MatExpr.isInvalid())
9421  return ExprError();
9422  commonExpr = MatExpr.get();
9423  }
9424 
9425  opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9426  commonExpr->getType(),
9427  commonExpr->getValueKind(),
9428  commonExpr->getObjectKind(),
9429  commonExpr);
9430  LHSExpr = CondExpr = opaqueValue;
9431  }
9432 
9433  QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9436  ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9437  QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9438  VK, OK, QuestionLoc);
9439  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9440  RHS.isInvalid())
9441  return ExprError();
9442 
9443  DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9444  RHS.get());
9445 
9446  CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9447 
9448  result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9449  Context);
9450 
9451  if (!commonExpr)
9452  return new (Context)
9453  ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9454  RHS.get(), result, VK, OK);
9455 
9456  return new (Context) BinaryConditionalOperator(
9457  commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9458  ColonLoc, result, VK, OK);
9459 }
9460 
9461 // Check if we have a conversion between incompatible cmse function pointer
9462 // types, that is, a conversion between a function pointer with the
9463 // cmse_nonsecure_call attribute and one without.
9465  QualType ToType) {
9466  if (const auto *ToFn =
9467  dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9468  if (const auto *FromFn =
9469  dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9470  FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9471  FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9472 
9473  return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9474  }
9475  }
9476  return false;
9477 }
9478 
9479 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9480 // being closely modeled after the C99 spec:-). The odd characteristic of this
9481 // routine is it effectively iqnores the qualifiers on the top level pointee.
9482 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9483 // FIXME: add a couple examples in this comment.
9486  SourceLocation Loc) {
9487  assert(LHSType.isCanonical() && "LHS not canonicalized!");
9488  assert(RHSType.isCanonical() && "RHS not canonicalized!");
9489 
9490  // get the "pointed to" type (ignoring qualifiers at the top level)
9491  const Type *lhptee, *rhptee;
9492  Qualifiers lhq, rhq;
9493  std::tie(lhptee, lhq) =
9494  cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9495  std::tie(rhptee, rhq) =
9496  cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9497 
9499 
9500  // C99 6.5.16.1p1: This following citation is common to constraints
9501  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9502  // qualifiers of the type *pointed to* by the right;
9503 
9504  // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9505  if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9506  lhq.compatiblyIncludesObjCLifetime(rhq)) {
9507  // Ignore lifetime for further calculation.
9508  lhq.removeObjCLifetime();
9509  rhq.removeObjCLifetime();
9510  }
9511 
9512  if (!lhq.compatiblyIncludes(rhq)) {
9513  // Treat address-space mismatches as fatal.
9514  if (!lhq.isAddressSpaceSupersetOf(rhq))
9516 
9517  // It's okay to add or remove GC or lifetime qualifiers when converting to
9518  // and from void*.
9519  else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9522  && (lhptee->isVoidType() || rhptee->isVoidType()))
9523  ; // keep old
9524 
9525  // Treat lifetime mismatches as fatal.
9526  else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9528 
9529  // For GCC/MS compatibility, other qualifier mismatches are treated
9530  // as still compatible in C.
9532  }
9533 
9534  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9535  // incomplete type and the other is a pointer to a qualified or unqualified
9536  // version of void...
9537  if (lhptee->isVoidType()) {
9538  if (rhptee->isIncompleteOrObjectType())
9539  return ConvTy;
9540 
9541  // As an extension, we allow cast to/from void* to function pointer.
9542  assert(rhptee->isFunctionType());
9544  }
9545 
9546  if (rhptee->isVoidType()) {
9547  if (lhptee->isIncompleteOrObjectType())
9548  return ConvTy;
9549 
9550  // As an extension, we allow cast to/from void* to function pointer.
9551  assert(lhptee->isFunctionType());
9553  }
9554 
9555  if (!S.Diags.isIgnored(
9556  diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9557  Loc) &&
9558  RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9559  !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9561 
9562  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9563  // unqualified versions of compatible types, ...
9564  QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9565  if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9566  // Check if the pointee types are compatible ignoring the sign.
9567  // We explicitly check for char so that we catch "char" vs
9568  // "unsigned char" on systems where "char" is unsigned.
9569  if (lhptee->isCharType())
9570  ltrans = S.Context.UnsignedCharTy;
9571  else if (lhptee->hasSignedIntegerRepresentation())
9572  ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9573 
9574  if (rhptee->isCharType())
9575  rtrans = S.Context.UnsignedCharTy;
9576  else if (rhptee->hasSignedIntegerRepresentation())
9577  rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9578 
9579  if (ltrans == rtrans) {
9580  // Types are compatible ignoring the sign. Qualifier incompatibility
9581  // takes priority over sign incompatibility because the sign
9582  // warning can be disabled.
9583  if (ConvTy != Sema::Compatible)
9584  return ConvTy;
9585 
9587  }
9588 
9589  // If we are a multi-level pointer, it's possible that our issue is simply
9590  // one of qualification - e.g. char ** -> const char ** is not allowed. If
9591  // the eventual target type is the same and the pointers have the same
9592  // level of indirection, this must be the issue.
9593  if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9594  do {
9595  std::tie(lhptee, lhq) =
9596  cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9597  std::tie(rhptee, rhq) =
9598  cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9599 
9600  // Inconsistent address spaces at this point is invalid, even if the
9601  // address spaces would be compatible.
9602  // FIXME: This doesn't catch address space mismatches for pointers of
9603  // different nesting levels, like:
9604  // __local int *** a;
9605  // int ** b = a;
9606  // It's not clear how to actually determine when such pointers are
9607  // invalidly incompatible.
9608  if (lhq.getAddressSpace() != rhq.getAddressSpace())
9610 
9611  } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9612 
9613  if (lhptee == rhptee)
9615  }
9616 
9617  // General pointer incompatibility takes priority over qualifiers.
9618  if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9621  }
9622  if (!S.getLangOpts().CPlusPlus &&
9623  S.IsFunctionConversion(ltrans, rtrans, ltrans))
9625  if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9627  return ConvTy;
9628 }
9629 
9630 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9631 /// block pointer types are compatible or whether a block and normal pointer
9632 /// are compatible. It is more restrict than comparing two function pointer
9633 // types.
9636  QualType RHSType) {
9637  assert(LHSType.isCanonical() && "LHS not canonicalized!");
9638  assert(RHSType.isCanonical() && "RHS not canonicalized!");
9639 
9640  QualType lhptee, rhptee;
9641 
9642  // get the "pointed to" type (ignoring qualifiers at the top level)
9643  lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9644  rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9645 
9646  // In C++, the types have to match exactly.
9647  if (S.getLangOpts().CPlusPlus)
9649 
9651 
9652  // For blocks we enforce that qualifiers are identical.
9653  Qualifiers LQuals = lhptee.getLocalQualifiers();
9654  Qualifiers RQuals = rhptee.getLocalQualifiers();
9655  if (S.getLangOpts().OpenCL) {
9656  LQuals.removeAddressSpace();
9657  RQuals.removeAddressSpace();
9658  }
9659  if (LQuals != RQuals)
9661 
9662  // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9663  // assignment.
9664  // The current behavior is similar to C++ lambdas. A block might be
9665  // assigned to a variable iff its return type and parameters are compatible
9666  // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9667  // an assignment. Presumably it should behave in way that a function pointer
9668  // assignment does in C, so for each parameter and return type:
9669  // * CVR and address space of LHS should be a superset of CVR and address
9670  // space of RHS.
9671  // * unqualified types should be compatible.
9672  if (S.getLangOpts().OpenCL) {
9674  S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9675  S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9677  } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9679 
9680  return ConvTy;
9681 }
9682 
9683 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9684 /// for assignment compatibility.
9687  QualType RHSType) {
9688  assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9689  assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9690 
9691  if (LHSType->isObjCBuiltinType()) {
9692  // Class is not compatible with ObjC object pointers.
9693  if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9694  !RHSType->isObjCQualifiedClassType())
9696  return Sema::Compatible;
9697  }
9698  if (RHSType->isObjCBuiltinType()) {
9699  if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9700  !LHSType->isObjCQualifiedClassType())
9702  return Sema::Compatible;
9703  }
9704  QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9705  QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9706 
9707  if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9708  // make an exception for id<P>
9709  !LHSType->isObjCQualifiedIdType())
9711 
9712  if (S.Context.typesAreCompatible(LHSType, RHSType))
9713  return Sema::Compatible;
9714  if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9717 }
9718 
9721  QualType LHSType, QualType RHSType) {
9722  // Fake up an opaque expression. We don't actually care about what
9723  // cast operations are required, so if CheckAssignmentConstraints
9724  // adds casts to this they'll be wasted, but fortunately that doesn't
9725  // usually happen on valid code.
9726  OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9727  ExprResult RHSPtr = &RHSExpr;
9728  CastKind K;
9729 
9730  return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9731 }
9732 
9733 /// This helper function returns true if QT is a vector type that has element
9734 /// type ElementType.
9735 static bool isVector(QualType QT, QualType ElementType) {
9736  if (const VectorType *VT = QT->getAs<VectorType>())
9737  return VT->getElementType().getCanonicalType() == ElementType;
9738  return false;
9739 }
9740 
9741 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9742 /// has code to accommodate several GCC extensions when type checking
9743 /// pointers. Here are some objectionable examples that GCC considers warnings:
9744 ///
9745 /// int a, *pint;
9746 /// short *pshort;
9747 /// struct foo *pfoo;
9748 ///
9749 /// pint = pshort; // warning: assignment from incompatible pointer type
9750 /// a = pint; // warning: assignment makes integer from pointer without a cast
9751 /// pint = a; // warning: assignment makes pointer from integer without a cast
9752 /// pint = pfoo; // warning: assignment from incompatible pointer type
9753 ///
9754 /// As a result, the code for dealing with pointers is more complex than the
9755 /// C99 spec dictates.
9756 ///
9757 /// Sets 'Kind' for any result kind except Incompatible.
9760  CastKind &Kind, bool ConvertRHS) {
9761  QualType RHSType = RHS.get()->getType();
9762  QualType OrigLHSType = LHSType;
9763 
9764  // Get canonical types. We're not formatting these types, just comparing
9765  // them.
9766  LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9767  RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9768 
9769  // Common case: no conversion required.
9770  if (LHSType == RHSType) {
9771  Kind = CK_NoOp;
9772  return Compatible;
9773  }
9774 
9775  // If the LHS has an __auto_type, there are no additional type constraints
9776  // to be worried about.
9777  if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9778  if (AT->isGNUAutoType()) {
9779  Kind = CK_NoOp;
9780  return Compatible;
9781  }
9782  }
9783 
9784  // If we have an atomic type, try a non-atomic assignment, then just add an
9785  // atomic qualification step.
9786  if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9787  Sema::AssignConvertType result =
9788  CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9789  if (result != Compatible)
9790  return result;
9791  if (Kind != CK_NoOp && ConvertRHS)
9792  RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9793  Kind = CK_NonAtomicToAtomic;
9794  return Compatible;
9795  }
9796 
9797  // If the left-hand side is a reference type, then we are in a
9798  // (rare!) case where we've allowed the use of references in C,
9799  // e.g., as a parameter type in a built-in function. In this case,
9800  // just make sure that the type referenced is compatible with the
9801  // right-hand side type. The caller is responsible for adjusting
9802  // LHSType so that the resulting expression does not have reference
9803  // type.
9804  if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9805  if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9806  Kind = CK_LValueBitCast;
9807  return Compatible;
9808  }
9809  return Incompatible;
9810  }
9811 
9812  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9813  // to the same ExtVector type.
9814  if (LHSType->isExtVectorType()) {
9815  if (RHSType->isExtVectorType())
9816  return Incompatible;
9817  if (RHSType->isArithmeticType()) {
9818  // CK_VectorSplat does T -> vector T, so first cast to the element type.
9819  if (ConvertRHS)
9820  RHS = prepareVectorSplat(LHSType, RHS.get());
9821  Kind = CK_VectorSplat;
9822  return Compatible;
9823  }
9824  }
9825 
9826  // Conversions to or from vector type.
9827  if (LHSType->isVectorType() || RHSType->isVectorType()) {
9828  if (LHSType->isVectorType() && RHSType->isVectorType()) {
9829  // Allow assignments of an AltiVec vector type to an equivalent GCC
9830  // vector type and vice versa
9831  if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9832  Kind = CK_BitCast;
9833  return Compatible;
9834  }
9835 
9836  // If we are allowing lax vector conversions, and LHS and RHS are both
9837  // vectors, the total size only needs to be the same. This is a bitcast;
9838  // no bits are changed but the result type is different.
9839  if (isLaxVectorConversion(RHSType, LHSType)) {
9840  // The default for lax vector conversions with Altivec vectors will
9841  // change, so if we are converting between vector types where
9842  // at least one is an Altivec vector, emit a warning.
9843  if (anyAltivecTypes(RHSType, LHSType) &&
9844  !areSameVectorElemTypes(RHSType, LHSType))
9845  Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9846  << RHSType << LHSType;
9847  Kind = CK_BitCast;
9848  return IncompatibleVectors;
9849  }
9850  }
9851 
9852  // When the RHS comes from another lax conversion (e.g. binops between
9853  // scalars and vectors) the result is canonicalized as a vector. When the
9854  // LHS is also a vector, the lax is allowed by the condition above. Handle
9855  // the case where LHS is a scalar.
9856  if (LHSType->isScalarType()) {
9857  const VectorType *VecType = RHSType->getAs<VectorType>();
9858  if (VecType && VecType->getNumElements() == 1 &&
9859  isLaxVectorConversion(RHSType, LHSType)) {
9860  if (VecType->getVectorKind() == VectorType::AltiVecVector)
9861  Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9862  << RHSType << LHSType;
9863  ExprResult *VecExpr = &RHS;
9864  *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9865  Kind = CK_BitCast;
9866  return Compatible;
9867  }
9868  }
9869 
9870  // Allow assignments between fixed-length and sizeless SVE vectors.
9871  if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9872  (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9873  if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9874  Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9875  Kind = CK_BitCast;
9876  return Compatible;
9877  }
9878 
9879  return Incompatible;
9880  }
9881 
9882  // Diagnose attempts to convert between __ibm128, __float128 and long double
9883  // where such conversions currently can't be handled.
9884  if (unsupportedTypeConversion(*this, LHSType, RHSType))
9885  return Incompatible;
9886 
9887  // Disallow assigning a _Complex to a real type in C++ mode since it simply
9888  // discards the imaginary part.
9889  if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9890  !LHSType->getAs<ComplexType>())
9891  return Incompatible;
9892 
9893  // Arithmetic conversions.
9894  if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9895  !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9896  if (ConvertRHS)
9897  Kind = PrepareScalarCast(RHS, LHSType);
9898  return Compatible;
9899  }
9900 
9901  // Conversions to normal pointers.
9902  if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9903  // U* -> T*
9904  if (isa<PointerType>(RHSType)) {
9905  LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9906  LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9907  if (AddrSpaceL != AddrSpaceR)
9908  Kind = CK_AddressSpaceConversion;
9909  else if (Context.hasCvrSimilarType(RHSType, LHSType))
9910  Kind = CK_NoOp;
9911  else
9912  Kind = CK_BitCast;
9913  return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9914  RHS.get()->getBeginLoc());
9915  }
9916 
9917  // int -> T*
9918  if (RHSType->isIntegerType()) {
9919  Kind = CK_IntegralToPointer; // FIXME: null?
9920  return IntToPointer;
9921  }
9922 
9923  // C pointers are not compatible with ObjC object pointers,
9924  // with two exceptions:
9925  if (isa<ObjCObjectPointerType>(RHSType)) {
9926  // - conversions to void*
9927  if (LHSPointer->getPointeeType()->isVoidType()) {
9928  Kind = CK_BitCast;
9929  return Compatible;
9930  }
9931 
9932  // - conversions from 'Class' to the redefinition type
9933  if (RHSType->isObjCClassType() &&
9934  Context.hasSameType(LHSType,
9936  Kind = CK_BitCast;
9937  return Compatible;
9938  }
9939 
9940  Kind = CK_BitCast;
9941  return IncompatiblePointer;
9942  }
9943 
9944  // U^ -> void*
9945  if (RHSType->getAs<BlockPointerType>()) {
9946  if (LHSPointer->getPointeeType()->isVoidType()) {
9947  LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9948  LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9949  ->getPointeeType()
9950  .getAddressSpace();
9951  Kind =
9952  AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9953  return Compatible;
9954  }
9955  }
9956 
9957  return Incompatible;
9958  }
9959 
9960  // Conversions to block pointers.
9961  if (isa<BlockPointerType>(LHSType)) {
9962  // U^ -> T^
9963  if (RHSType->isBlockPointerType()) {
9964  LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9965  ->getPointeeType()
9966  .getAddressSpace();
9967  LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9968  ->getPointeeType()
9969  .getAddressSpace();
9970  Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9971  return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9972  }
9973 
9974  // int or null -> T^
9975  if (RHSType->isIntegerType()) {
9976  Kind = CK_IntegralToPointer; // FIXME: null
9977  return IntToBlockPointer;
9978  }
9979 
9980  // id -> T^
9981  if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9982  Kind = CK_AnyPointerToBlockPointerCast;
9983  return Compatible;
9984  }
9985 
9986  // void* -> T^
9987  if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9988  if (RHSPT->getPointeeType()->isVoidType()) {
9989  Kind = CK_AnyPointerToBlockPointerCast;
9990  return Compatible;
9991  }
9992 
9993  return Incompatible;
9994  }
9995 
9996  // Conversions to Objective-C pointers.
9997  if (isa<ObjCObjectPointerType>(LHSType)) {
9998  // A* -> B*
9999  if (RHSType->isObjCObjectPointerType()) {
10000  Kind = CK_BitCast;
10001  Sema::AssignConvertType result =
10002  checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
10003  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10004  result == Compatible &&
10005  !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
10006  result = IncompatibleObjCWeakRef;
10007  return result;
10008  }
10009 
10010  // int or null -> A*
10011  if (RHSType->isIntegerType()) {
10012  Kind = CK_IntegralToPointer; // FIXME: null
10013  return IntToPointer;
10014  }
10015 
10016  // In general, C pointers are not compatible with ObjC object pointers,
10017  // with two exceptions:
10018  if (isa<PointerType>(RHSType)) {
10019  Kind = CK_CPointerToObjCPointerCast;
10020 
10021  // - conversions from 'void*'
10022  if (RHSType->isVoidPointerType()) {
10023  return Compatible;
10024  }
10025 
10026  // - conversions to 'Class' from its redefinition type
10027  if (LHSType->isObjCClassType() &&
10028  Context.hasSameType(RHSType,
10030  return Compatible;
10031  }
10032 
10033  return IncompatiblePointer;
10034  }
10035 
10036  // Only under strict condition T^ is compatible with an Objective-C pointer.
10037  if (RHSType->isBlockPointerType() &&
10039  if (ConvertRHS)
10041  Kind = CK_BlockPointerToObjCPointerCast;
10042  return Compatible;
10043  }
10044 
10045  return Incompatible;
10046  }
10047 
10048  // Conversions from pointers that are not covered by the above.
10049  if (isa<PointerType>(RHSType)) {
10050  // T* -> _Bool
10051  if (LHSType == Context.BoolTy) {
10052  Kind = CK_PointerToBoolean;
10053  return Compatible;
10054  }
10055 
10056  // T* -> int
10057  if (LHSType->isIntegerType()) {
10058  Kind = CK_PointerToIntegral;
10059  return PointerToInt;
10060  }
10061 
10062  return Incompatible;
10063  }
10064 
10065  // Conversions from Objective-C pointers that are not covered by the above.
10066  if (isa<ObjCObjectPointerType>(RHSType)) {
10067  // T* -> _Bool
10068  if (LHSType == Context.BoolTy) {
10069  Kind = CK_PointerToBoolean;
10070  return Compatible;
10071  }
10072 
10073  // T* -> int
10074  if (LHSType->isIntegerType()) {
10075  Kind = CK_PointerToIntegral;
10076  return PointerToInt;
10077  }
10078 
10079  return Incompatible;
10080  }
10081 
10082  // struct A -> struct B
10083  if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10084  if (Context.typesAreCompatible(LHSType, RHSType)) {
10085  Kind = CK_NoOp;
10086  return Compatible;
10087  }
10088  }
10089 
10090  if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10091  Kind = CK_IntToOCLSampler;
10092  return Compatible;
10093  }
10094 
10095  return Incompatible;
10096 }
10097 
10098 /// Constructs a transparent union from an expression that is
10099 /// used to initialize the transparent union.
10101  ExprResult &EResult, QualType UnionType,
10102  FieldDecl *Field) {
10103  // Build an initializer list that designates the appropriate member
10104  // of the transparent union.
10105  Expr *E = EResult.get();
10107  E, SourceLocation());
10108  Initializer->setType(UnionType);
10109  Initializer->setInitializedFieldInUnion(Field);
10110 
10111  // Build a compound literal constructing a value of the transparent
10112  // union type from this initializer list.
10113  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10114  EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10115  VK_PRValue, Initializer, false);
10116 }
10117 
10120  ExprResult &RHS) {
10121  QualType RHSType = RHS.get()->getType();
10122 
10123  // If the ArgType is a Union type, we want to handle a potential
10124  // transparent_union GCC extension.
10125  const RecordType *UT = ArgType->getAsUnionType();
10126  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
10127  return Incompatible;
10128 
10129  // The field to initialize within the transparent union.
10130  RecordDecl *UD = UT->getDecl();
10131  FieldDecl *InitField = nullptr;
10132  // It's compatible if the expression matches any of the fields.
10133  for (auto *it : UD->fields()) {
10134  if (it->getType()->isPointerType()) {
10135  // If the transparent union contains a pointer type, we allow:
10136  // 1) void pointer
10137  // 2) null pointer constant
10138  if (RHSType->isPointerType())
10139  if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10140  RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10141  InitField = it;
10142  break;
10143  }
10144 
10145  if (RHS.get()->isNullPointerConstant(Context,
10147  RHS = ImpCastExprToType(RHS.get(), it->getType(),
10148  CK_NullToPointer);
10149  InitField = it;
10150  break;
10151  }
10152  }
10153 
10154  CastKind Kind;
10155  if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
10156  == Compatible) {
10157  RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10158  InitField = it;
10159  break;
10160  }
10161  }
10162 
10163  if (!InitField)
10164  return Incompatible;
10165 
10166  ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10167  return Compatible;
10168 }
10169 
10172  bool Diagnose,
10173  bool DiagnoseCFAudited,
10174  bool ConvertRHS) {
10175  // We need to be able to tell the caller whether we diagnosed a problem, if
10176  // they ask us to issue diagnostics.
10177  assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10178 
10179  // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10180  // we can't avoid *all* modifications at the moment, so we need some somewhere
10181  // to put the updated value.
10182  ExprResult LocalRHS = CallerRHS;
10183  ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10184 
10185  if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10186  if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10187  if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10188  !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10189  Diag(RHS.get()->getExprLoc(),
10190  diag::warn_noderef_to_dereferenceable_pointer)
10191  << RHS.get()->getSourceRange();
10192  }
10193  }
10194  }
10195 
10196  if (getLangOpts().CPlusPlus) {
10197  if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10198  // C++ 5.17p3: If the left operand is not of class type, the
10199  // expression is implicitly converted (C++ 4) to the
10200  // cv-unqualified type of the left operand.
10201  QualType RHSType = RHS.get()->getType();
10202  if (Diagnose) {
10203  RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10204  AA_Assigning);
10205  } else {
10207  TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10208  /*SuppressUserConversions=*/false,
10210  /*InOverloadResolution=*/false,
10211  /*CStyle=*/false,
10212  /*AllowObjCWritebackConversion=*/false);
10213  if (ICS.isFailure())
10214  return Incompatible;
10215  RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10216  ICS, AA_Assigning);
10217  }
10218  if (RHS.isInvalid())
10219  return Incompatible;
10221  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10222  !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10223  result = IncompatibleObjCWeakRef;
10224  return result;
10225  }
10226 
10227  // FIXME: Currently, we fall through and treat C++ classes like C
10228  // structures.
10229  // FIXME: We also fall through for atomics; not sure what should
10230  // happen there, though.
10231  } else if (RHS.get()->getType() == Context.OverloadTy) {
10232  // As a set of extensions to C, we support overloading on functions. These
10233  // functions need to be resolved here.
10234  DeclAccessPair DAP;
10236  RHS.get(), LHSType, /*Complain=*/false, DAP))
10237  RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10238  else
10239  return Incompatible;
10240  }
10241 
10242  // This check seems unnatural, however it is necessary to ensure the proper
10243  // conversion of functions/arrays. If the conversion were done for all
10244  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10245  // expressions that suppress this implicit conversion (&, sizeof). This needs
10246  // to happen before we check for null pointer conversions because C does not
10247  // undergo the same implicit conversions as C++ does above (by the calls to
10248  // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10249  // lvalue to rvalue cast before checking for null pointer constraints. This
10250  // addresses code like: nullptr_t val; int *ptr; ptr = val;
10251  //
10252  // Suppress this for references: C++ 8.5.3p5.
10253  if (!LHSType->isReferenceType()) {
10254  // FIXME: We potentially allocate here even if ConvertRHS is false.
10255  RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
10256  if (RHS.isInvalid())
10257  return Incompatible;
10258  }
10259 
10260  // C99 6.5.16.1p1: the left operand is a pointer and the right is
10261  // a null pointer constant.
10262  if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
10263  LHSType->isBlockPointerType()) &&
10266  if (Diagnose || ConvertRHS) {
10267  CastKind Kind;
10268  CXXCastPath Path;
10269  CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10270  /*IgnoreBaseAccess=*/false, Diagnose);
10271  if (ConvertRHS)
10272  RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10273  }
10274  return Compatible;
10275  }
10276 
10277  // OpenCL queue_t type assignment.
10278  if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10280  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10281  return Compatible;
10282  }
10283 
10284  CastKind Kind;
10285  Sema::AssignConvertType result =
10286  CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10287 
10288  // C99 6.5.16.1p2: The value of the right operand is converted to the
10289  // type of the assignment expression.
10290  // CheckAssignmentConstraints allows the left-hand side to be a reference,
10291  // so that we can use references in built-in functions even in C.
10292  // The getNonReferenceType() call makes sure that the resulting expression
10293  // does not have reference type.
10294  if (result != Incompatible && RHS.get()->getType() != LHSType) {
10295  QualType Ty = LHSType.getNonLValueExprType(Context);
10296  Expr *E = RHS.get();
10297 
10298  // Check for various Objective-C errors. If we are not reporting
10299  // diagnostics and just checking for errors, e.g., during overload
10300  // resolution, return Incompatible to indicate the failure.
10301  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10303  Diagnose, DiagnoseCFAudited) != ACR_okay) {
10304  if (!Diagnose)
10305  return Incompatible;
10306  }
10307  if (getLangOpts().ObjC &&
10309  E->getType(), E, Diagnose) ||
10310  CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10311  if (!Diagnose)
10312  return Incompatible;
10313  // Replace the expression with a corrected version and continue so we
10314  // can find further errors.
10315  RHS = E;
10316  return Compatible;
10317  }
10318 
10319  if (ConvertRHS)
10320  RHS = ImpCastExprToType(E, Ty, Kind);
10321  }
10322 
10323  return result;
10324 }
10325 
10326 namespace {
10327 /// The original operand to an operator, prior to the application of the usual
10328 /// arithmetic conversions and converting the arguments of a builtin operator
10329 /// candidate.
10330 struct OriginalOperand {
10331  explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10332  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10333  Op = MTE->getSubExpr();
10334  if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10335  Op = BTE->getSubExpr();
10336  if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10337  Orig = ICE->getSubExprAsWritten();
10338  Conversion = ICE->getConversionFunction();
10339  }
10340  }
10341 
10342  QualType getType() const { return Orig->getType(); }
10343 
10344  Expr *Orig;
10345  NamedDecl *Conversion;
10346 };
10347 }
10348 
10350  ExprResult &RHS) {
10351  OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10352 
10353  Diag(Loc, diag::err_typecheck_invalid_operands)
10354  << OrigLHS.getType() << OrigRHS.getType()
10355  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10356 
10357  // If a user-defined conversion was applied to either of the operands prior
10358  // to applying the built-in operator rules, tell the user about it.
10359  if (OrigLHS.Conversion) {
10360  Diag(OrigLHS.Conversion->getLocation(),
10361  diag::note_typecheck_invalid_operands_converted)
10362  << 0 << LHS.get()->getType();
10363  }
10364  if (OrigRHS.Conversion) {
10365  Diag(OrigRHS.Conversion->getLocation(),
10366  diag::note_typecheck_invalid_operands_converted)
10367  << 1 << RHS.get()->getType();
10368  }
10369 
10370  return QualType();
10371 }
10372 
10373 // Diagnose cases where a scalar was implicitly converted to a vector and
10374 // diagnose the underlying types. Otherwise, diagnose the error
10375 // as invalid vector logical operands for non-C++ cases.
10377  ExprResult &RHS) {
10378  QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10379  QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10380 
10381  bool LHSNatVec = LHSType->isVectorType();
10382  bool RHSNatVec = RHSType->isVectorType();
10383 
10384  if (!(LHSNatVec && RHSNatVec)) {
10385  Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10386  Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10387  Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10388  << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10389  << Vector->getSourceRange();
10390  return QualType();
10391  }
10392 
10393  Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10394  << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10395  << RHS.get()->getSourceRange();
10396 
10397  return QualType();
10398 }
10399 
10400 /// Try to convert a value of non-vector type to a vector type by converting
10401 /// the type to the element type of the vector and then performing a splat.
10402 /// If the language is OpenCL, we only use conversions that promote scalar
10403 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10404 /// for float->int.
10405 ///
10406 /// OpenCL V2.0 6.2.6.p2:
10407 /// An error shall occur if any scalar operand type has greater rank
10408 /// than the type of the vector element.
10409 ///
10410 /// \param scalar - if non-null, actually perform the conversions
10411 /// \return true if the operation fails (but without diagnosing the failure)
10412 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10413  QualType scalarTy,
10414  QualType vectorEltTy,
10415  QualType vectorTy,
10416  unsigned &DiagID) {
10417  // The conversion to apply to the scalar before splatting it,
10418  // if necessary.
10419  CastKind scalarCast = CK_NoOp;
10420 
10421  if (vectorEltTy->isIntegralType(S.Context)) {
10422  if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10423  (scalarTy->isIntegerType() &&
10424  S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10425  DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10426  return true;
10427  }
10428  if (!scalarTy->isIntegralType(S.Context))
10429  return true;
10430  scalarCast = CK_IntegralCast;
10431  } else if (vectorEltTy->isRealFloatingType()) {
10432  if (scalarTy->isRealFloatingType()) {
10433  if (S.getLangOpts().OpenCL &&
10434  S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10435  DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10436  return true;
10437  }
10438  scalarCast = CK_FloatingCast;
10439  }
10440  else if (scalarTy->isIntegralType(S.Context))
10441  scalarCast = CK_IntegralToFloating;
10442  else
10443  return true;
10444  } else {
10445  return true;
10446  }
10447 
10448  // Adjust scalar if desired.
10449  if (scalar) {
10450  if (scalarCast != CK_NoOp)
10451  *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10452  *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10453  }
10454  return false;
10455 }
10456 
10457 /// Convert vector E to a vector with the same number of elements but different
10458 /// element type.
10459 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10460  const auto *VecTy = E->getType()->getAs<VectorType>();
10461  assert(VecTy && "Expression E must be a vector");
10462  QualType NewVecTy =
10463  VecTy->isExtVectorType()
10464  ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10465  : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10466  VecTy->getVectorKind());
10467 
10468  // Look through the implicit cast. Return the subexpression if its type is
10469  // NewVecTy.
10470  if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10471  if (ICE->getSubExpr()->getType() == NewVecTy)
10472  return ICE->getSubExpr();
10473 
10474  auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10475  return S.ImpCastExprToType(E, NewVecTy, Cast);
10476 }
10477 
10478 /// Test if a (constant) integer Int can be casted to another integer type
10479 /// IntTy without losing precision.
10481  QualType OtherIntTy) {
10482  QualType IntTy = Int->get()->getType().getUnqualifiedType();
10483 
10484  // Reject cases where the value of the Int is unknown as that would
10485  // possibly cause truncation, but accept cases where the scalar can be
10486  // demoted without loss of precision.
10487  Expr::EvalResult EVResult;
10488  bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10489  int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10490  bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10491  bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10492 
10493  if (CstInt) {
10494  // If the scalar is constant and is of a higher order and has more active
10495  // bits that the vector element type, reject it.
10496  llvm::APSInt Result = EVResult.Val.getInt();
10497  unsigned NumBits = IntSigned
10498  ? (Result.isNegative() ? Result.getMinSignedBits()
10499  : Result.getActiveBits())
10500  : Result.getActiveBits();
10501  if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10502  return true;
10503 
10504  // If the signedness of the scalar type and the vector element type
10505  // differs and the number of bits is greater than that of the vector
10506  // element reject it.
10507  return (IntSigned != OtherIntSigned &&
10508  NumBits > S.Context.getIntWidth(OtherIntTy));
10509  }
10510 
10511  // Reject cases where the value of the scalar is not constant and it's
10512  // order is greater than that of the vector element type.
10513  return (Order < 0);
10514 }
10515 
10516 /// Test if a (constant) integer Int can be casted to floating point type
10517 /// FloatTy without losing precision.
10519  QualType FloatTy) {
10520  QualType IntTy = Int->get()->getType().getUnqualifiedType();
10521 
10522  // Determine if the integer constant can be expressed as a floating point
10523  // number of the appropriate type.
10524  Expr::EvalResult EVResult;
10525  bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10526 
10527  uint64_t Bits = 0;
10528  if (CstInt) {
10529  // Reject constants that would be truncated if they were converted to
10530  // the floating point type. Test by simple to/from conversion.
10531  // FIXME: Ideally the conversion to an APFloat and from an APFloat
10532  // could be avoided if there was a convertFromAPInt method
10533  // which could signal back if implicit truncation occurred.
10534  llvm::APSInt Result = EVResult.Val.getInt();
10535  llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10536  Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10537  llvm::APFloat::rmTowardZero);
10538  llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10539  !IntTy->hasSignedIntegerRepresentation());
10540  bool Ignored = false;
10541  Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10542  &Ignored);
10543  if (Result != ConvertBack)
10544  return true;
10545  } else {
10546  // Reject types that cannot be fully encoded into the mantissa of
10547  // the float.
10548  Bits = S.Context.getTypeSize(IntTy);
10549  unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10550  S.Context.getFloatTypeSemantics(FloatTy));
10551  if (Bits > FloatPrec)
10552  return true;
10553  }
10554 
10555  return false;
10556 }
10557 
10558 /// Attempt to convert and splat Scalar into a vector whose types matches
10559 /// Vector following GCC conversion rules. The rule is that implicit
10560 /// conversion can occur when Scalar can be casted to match Vector's element
10561 /// type without causing truncation of Scalar.
10563  ExprResult *Vector) {
10564  QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10565  QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10566  QualType VectorEltTy;
10567 
10568  if (const auto *VT = VectorTy->getAs<VectorType>()) {
10569  assert(!isa<ExtVectorType>(VT) &&
10570  "ExtVectorTypes should not be handled here!");
10571  VectorEltTy = VT->getElementType();
10572  } else if (VectorTy->isVLSTBuiltinType()) {
10573  VectorEltTy =
10574  VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10575  } else {
10576  llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10577  }
10578 
10579  // Reject cases where the vector element type or the scalar element type are
10580  // not integral or floating point types.
10581  if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10582  return true;
10583 
10584  // The conversion to apply to the scalar before splatting it,
10585  // if necessary.
10586  CastKind ScalarCast = CK_NoOp;
10587 
10588  // Accept cases where the vector elements are integers and the scalar is
10589  // an integer.
10590  // FIXME: Notionally if the scalar was a floating point value with a precise
10591  // integral representation, we could cast it to an appropriate integer
10592  // type and then perform the rest of the checks here. GCC will perform
10593  // this conversion in some cases as determined by the input language.
10594  // We should accept it on a language independent basis.
10595  if (VectorEltTy->isIntegralType(S.Context) &&
10596  ScalarTy->isIntegralType(S.Context) &&
10597  S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10598 
10599  if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10600  return true;
10601 
10602  ScalarCast = CK_IntegralCast;
10603  } else if (VectorEltTy->isIntegralType(S.Context) &&
10604  ScalarTy->isRealFloatingType()) {
10605  if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10606  ScalarCast = CK_FloatingToIntegral;
10607  else
10608  return true;
10609  } else if (VectorEltTy->isRealFloatingType()) {
10610  if (ScalarTy->isRealFloatingType()) {
10611 
10612  // Reject cases where the scalar type is not a constant and has a higher
10613  // Order than the vector element type.
10614  llvm::APFloat Result(0.0);
10615 
10616  // Determine whether this is a constant scalar. In the event that the
10617  // value is dependent (and thus cannot be evaluated by the constant
10618  // evaluator), skip the evaluation. This will then diagnose once the
10619  // expression is instantiated.
10620  bool CstScalar = Scalar->get()->isValueDependent() ||
10621  Scalar->get()->EvaluateAsFloat(Result, S.Context);
10622  int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10623  if (!CstScalar && Order < 0)
10624  return true;
10625 
10626  // If the scalar cannot be safely casted to the vector element type,
10627  // reject it.
10628  if (CstScalar) {
10629  bool Truncated = false;
10630  Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10631  llvm::APFloat::rmNearestTiesToEven, &Truncated);
10632  if (Truncated)
10633  return true;
10634  }
10635 
10636  ScalarCast = CK_FloatingCast;
10637  } else if (ScalarTy->isIntegralType(S.Context)) {
10638  if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10639  return true;
10640 
10641  ScalarCast = CK_IntegralToFloating;
10642  } else
10643  return true;
10644  } else if (ScalarTy->isEnumeralType())
10645  return true;
10646 
10647  // Adjust scalar if desired.
10648  if (Scalar) {
10649  if (ScalarCast != CK_NoOp)
10650  *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10651  *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10652  }
10653  return false;
10654 }
10655 
10657  SourceLocation Loc, bool IsCompAssign,
10658  bool AllowBothBool,
10659  bool AllowBoolConversions,
10660  bool AllowBoolOperation,
10661  bool ReportInvalid) {
10662  if (!IsCompAssign) {
10664  if (LHS.isInvalid())
10665  return QualType();
10666  }
10668  if (RHS.isInvalid())
10669  return QualType();
10670 
10671  // For conversion purposes, we ignore any qualifiers.
10672  // For example, "const float" and "float" are equivalent.
10673  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10674  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10675 
10676  const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10677  const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10678  assert(LHSVecType || RHSVecType);
10679 
10680  if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10681  (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10682  return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10683 
10684  // AltiVec-style "vector bool op vector bool" combinations are allowed
10685  // for some operators but not others.
10686  if (!AllowBothBool &&
10687  LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10688  RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10689  return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10690 
10691  // This operation may not be performed on boolean vectors.
10692  if (!AllowBoolOperation &&
10693  (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10694  return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10695 
10696  // If the vector types are identical, return.
10697  if (Context.hasSameType(LHSType, RHSType))
10698  return Context.getCommonSugaredType(LHSType, RHSType);
10699 
10700  // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10701  if (LHSVecType && RHSVecType &&
10702  Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10703  if (isa<ExtVectorType>(LHSVecType)) {
10704  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10705  return LHSType;
10706  }
10707 
10708  if (!IsCompAssign)
10709  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10710  return RHSType;
10711  }
10712 
10713  // AllowBoolConversions says that bool and non-bool AltiVec vectors
10714  // can be mixed, with the result being the non-bool type. The non-bool
10715  // operand must have integer element type.
10716  if (AllowBoolConversions && LHSVecType && RHSVecType &&
10717  LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10718  (Context.getTypeSize(LHSVecType->getElementType()) ==
10719  Context.getTypeSize(RHSVecType->getElementType()))) {
10720  if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10721  LHSVecType->getElementType()->isIntegerType() &&
10722  RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10723  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10724  return LHSType;
10725  }
10726  if (!IsCompAssign &&
10727  LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10728  RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10729  RHSVecType->getElementType()->isIntegerType()) {
10730  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10731  return RHSType;
10732  }
10733  }
10734 
10735  // Expressions containing fixed-length and sizeless SVE vectors are invalid
10736  // since the ambiguity can affect the ABI.
10737  auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10738  const VectorType *VecType = SecondType->getAs<VectorType>();
10739  return FirstType->isSizelessBuiltinType() && VecType &&
10741  VecType->getVectorKind() ==
10743  };
10744 
10745  if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10746  Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10747  return QualType();
10748  }
10749 
10750  // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10751  // since the ambiguity can affect the ABI.
10752  auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10753  const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10754  const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10755 
10756  if (FirstVecType && SecondVecType)
10757  return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10758  (SecondVecType->getVectorKind() ==
10760  SecondVecType->getVectorKind() ==
10762 
10763  return FirstType->isSizelessBuiltinType() && SecondVecType &&
10764  SecondVecType->getVectorKind() == VectorType::GenericVector;
10765  };
10766 
10767  if (IsSveGnuConversion(LHSType, RHSType) ||
10768  IsSveGnuConversion(RHSType, LHSType)) {
10769  Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10770  return QualType();
10771  }
10772 
10773  // If there's a vector type and a scalar, try to convert the scalar to
10774  // the vector element type and splat.
10775  unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10776  if (!RHSVecType) {
10777  if (isa<ExtVectorType>(LHSVecType)) {
10778  if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10779  LHSVecType->getElementType(), LHSType,
10780  DiagID))
10781  return LHSType;
10782  } else {
10783  if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10784  return LHSType;
10785  }
10786  }
10787  if (!LHSVecType) {
10788  if (isa<ExtVectorType>(RHSVecType)) {
10789  if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10790  LHSType, RHSVecType->getElementType(),
10791  RHSType, DiagID))
10792  return RHSType;
10793  } else {
10794  if (LHS.get()->isLValue() ||
10795  !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10796  return RHSType;
10797  }
10798  }
10799 
10800  // FIXME: The code below also handles conversion between vectors and
10801  // non-scalars, we should break this down into fine grained specific checks
10802  // and emit proper diagnostics.
10803  QualType VecType = LHSVecType ? LHSType : RHSType;
10804  const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10805  QualType OtherType = LHSVecType ? RHSType : LHSType;
10806  ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10807  if (isLaxVectorConversion(OtherType, VecType)) {
10808  if (anyAltivecTypes(RHSType, LHSType) &&
10809  !areSameVectorElemTypes(RHSType, LHSType))
10810  Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10811  // If we're allowing lax vector conversions, only the total (data) size
10812  // needs to be the same. For non compound assignment, if one of the types is
10813  // scalar, the result is always the vector type.
10814  if (!IsCompAssign) {
10815  *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10816  return VecType;
10817  // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10818  // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10819  // type. Note that this is already done by non-compound assignments in
10820  // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10821  // <1 x T> -> T. The result is also a vector type.
10822  } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10823  (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10824  ExprResult *RHSExpr = &RHS;
10825  *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10826  return VecType;
10827  }
10828  }
10829 
10830  // Okay, the expression is invalid.
10831 
10832  // If there's a non-vector, non-real operand, diagnose that.
10833  if ((!RHSVecType && !RHSType->isRealType()) ||
10834  (!LHSVecType && !LHSType->isRealType())) {
10835  Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10836  << LHSType << RHSType
10837  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10838  return QualType();
10839  }
10840 
10841  // OpenCL V1.1 6.2.6.p1:
10842  // If the operands are of more than one vector type, then an error shall
10843  // occur. Implicit conversions between vector types are not permitted, per
10844  // section 6.2.1.
10845  if (getLangOpts().OpenCL &&
10846  RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10847  LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10848  Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10849  << RHSType;
10850  return QualType();
10851  }
10852 
10853 
10854  // If there is a vector type that is not a ExtVector and a scalar, we reach
10855  // this point if scalar could not be converted to the vector's element type
10856  // without truncation.
10857  if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10858  (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10859  QualType Scalar = LHSVecType ? RHSType : LHSType;
10860  QualType Vector = LHSVecType ? LHSType : RHSType;
10861  unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10862  Diag(Loc,
10863  diag::err_typecheck_vector_not_convertable_implict_truncation)
10864  << ScalarOrVector << Scalar << Vector;
10865 
10866  return QualType();
10867  }
10868 
10869  // Otherwise, use the generic diagnostic.
10870  Diag(Loc, DiagID)
10871  << LHSType << RHSType
10872  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10873  return QualType();
10874 }
10875 
10877  SourceLocation Loc,
10878  bool IsCompAssign,
10879  ArithConvKind OperationKind) {
10880  if (!IsCompAssign) {
10882  if (LHS.isInvalid())
10883  return QualType();
10884  }
10886  if (RHS.isInvalid())
10887  return QualType();
10888 
10889  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10890  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10891 
10892  const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10893  const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10894 
10895  unsigned DiagID = diag::err_typecheck_invalid_operands;
10896  if ((OperationKind == ACK_Arithmetic) &&
10897  ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10898  (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10899  Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10900  << RHS.get()->getSourceRange();
10901  return QualType();
10902  }
10903 
10904  if (Context.hasSameType(LHSType, RHSType))
10905  return LHSType;
10906 
10907  if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
10908  if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10909  return LHSType;
10910  }
10911  if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
10912  if (LHS.get()->isLValue() ||
10913  !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10914  return RHSType;
10915  }
10916 
10917  if ((!LHSType->isVLSTBuiltinType() && !LHSType->isRealType()) ||
10918  (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) {
10919  Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10920  << LHSType << RHSType << LHS.get()->getSourceRange()
10921  << RHS.get()->getSourceRange();
10922  return QualType();
10923  }
10924 
10925  if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
10926  Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10927  Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10928  Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10929  << LHSType << RHSType << LHS.get()->getSourceRange()
10930  << RHS.get()->getSourceRange();
10931  return QualType();
10932  }
10933 
10934  if (LHSType->isVLSTBuiltinType() || RHSType->isVLSTBuiltinType()) {
10935  QualType Scalar = LHSType->isVLSTBuiltinType() ? RHSType : LHSType;
10936  QualType Vector = LHSType->isVLSTBuiltinType() ? LHSType : RHSType;
10937  bool ScalarOrVector =
10938  LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType();
10939 
10940  Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10941  << ScalarOrVector << Scalar << Vector;
10942 
10943  return QualType();
10944  }
10945 
10946  Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10947  << RHS.get()->getSourceRange();
10948  return QualType();
10949 }
10950 
10951 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10952 // expression. These are mainly cases where the null pointer is used as an
10953 // integer instead of a pointer.
10954 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10955  SourceLocation Loc, bool IsCompare) {
10956  // The canonical way to check for a GNU null is with isNullPointerConstant,
10957  // but we use a bit of a hack here for speed; this is a relatively
10958  // hot path, and isNullPointerConstant is slow.
10959  bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10960  bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10961 
10962  QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10963 
10964  // Avoid analyzing cases where the result will either be invalid (and
10965  // diagnosed as such) or entirely valid and not something to warn about.
10966  if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10967  NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10968  return;
10969 
10970  // Comparison operations would not make sense with a null pointer no matter
10971  // what the other expression is.
10972  if (!IsCompare) {
10973  S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10974  << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10975  << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10976  return;
10977  }
10978 
10979  // The rest of the operations only make sense with a null pointer
10980  // if the other expression is a pointer.
10981  if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10982  NonNullType->canDecayToPointerType())
10983  return;
10984 
10985  S.Diag(Loc, diag::warn_null_in_comparison_operation)
10986  << LHSNull /* LHS is NULL */ << NonNullType
10987  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10988 }
10989 
10991  SourceLocation Loc) {
10992  const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10993  const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10994  if (!LUE || !RUE)
10995  return;
10996  if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10997  RUE->getKind() != UETT_SizeOf)
10998  return;
10999 
11000  const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11001  QualType LHSTy = LHSArg->getType();
11002  QualType RHSTy;
11003 
11004  if (RUE->isArgumentType())
11005  RHSTy = RUE->getArgumentType().getNonReferenceType();
11006  else
11007  RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11008 
11009  if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11010  if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11011  return;
11012 
11013  S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11014  if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11015  if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11016  S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11017  << LHSArgDecl;
11018  }
11019  } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11020  QualType ArrayElemTy = ArrayTy->getElementType();
11021  if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11022  ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11023  RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11024  S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11025  return;
11026  S.Diag(Loc, diag::warn_division_sizeof_array)
11027  << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11028  if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11029  if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11030  S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11031  << LHSArgDecl;
11032  }
11033 
11034  S.Diag(Loc, diag::note_precedence_silence) << RHS;
11035  }
11036 }
11037 
11039  ExprResult &RHS,
11040  SourceLocation Loc, bool IsDiv) {
11041  // Check for division/remainder by zero.
11042  Expr::EvalResult RHSValue;
11043  if (!RHS.get()->isValueDependent() &&
11044  RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11045  RHSValue.Val.getInt() == 0)
11046  S.DiagRuntimeBehavior(Loc, RHS.get(),
11047  S.PDiag(diag::warn_remainder_division_by_zero)
11048  << IsDiv << RHS.get()->getSourceRange());
11049 }
11050 
11052  SourceLocation Loc,
11053  bool IsCompAssign, bool IsDiv) {
11054  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11055 
11056  QualType LHSTy = LHS.get()->getType();
11057  QualType RHSTy = RHS.get()->getType();
11058  if (LHSTy->isVectorType() || RHSTy->isVectorType())
11059  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11060  /*AllowBothBool*/ getLangOpts().AltiVec,
11061  /*AllowBoolConversions*/ false,
11062  /*AllowBooleanOperation*/ false,
11063  /*ReportInvalid*/ true);
11064  if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
11065  return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11066  ACK_Arithmetic);
11067  if (!IsDiv &&
11068  (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11069  return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11070  // For division, only matrix-by-scalar is supported. Other combinations with
11071  // matrix types are invalid.
11072  if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11073  return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11074 
11076  LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11077  if (LHS.isInvalid() || RHS.isInvalid())
11078  return QualType();
11079 
11080 
11081  if (compType.isNull() || !compType->isArithmeticType())
11082  return InvalidOperands(Loc, LHS, RHS);
11083  if (IsDiv) {
11084  DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11085  DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11086  }
11087  return compType;
11088 }
11089 
11091  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11092  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11093 
11094  if (LHS.get()->getType()->isVectorType() ||
11095  RHS.get()->getType()->isVectorType()) {
11096  if (LHS.get()->getType()->hasIntegerRepresentation() &&
11097  RHS.get()->getType()->hasIntegerRepresentation())
11098  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11099  /*AllowBothBool*/ getLangOpts().AltiVec,
11100  /*AllowBoolConversions*/ false,
11101  /*AllowBooleanOperation*/ false,
11102  /*ReportInvalid*/ true);
11103  return InvalidOperands(Loc, LHS, RHS);
11104  }
11105 
11106  if (LHS.get()->getType()->isVLSTBuiltinType() ||
11107  RHS.get()->getType()->isVLSTBuiltinType()) {
11108  if (LHS.get()->getType()->hasIntegerRepresentation() &&
11109  RHS.get()->getType()->hasIntegerRepresentation())
11110  return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11111  ACK_Arithmetic);
11112 
11113  return InvalidOperands(Loc, LHS, RHS);
11114  }
11115 
11117  LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11118  if (LHS.isInvalid() || RHS.isInvalid())
11119  return QualType();
11120 
11121  if (compType.isNull() || !compType->isIntegerType())
11122  return InvalidOperands(Loc, LHS, RHS);
11123  DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11124  return compType;
11125 }
11126 
11127 /// Diagnose invalid arithmetic on two void pointers.
11129  Expr *LHSExpr, Expr *RHSExpr) {
11130  S.Diag(Loc, S.getLangOpts().CPlusPlus
11131  ? diag::err_typecheck_pointer_arith_void_type
11132  : diag::ext_gnu_void_ptr)
11133  << 1 /* two pointers */ << LHSExpr->getSourceRange()
11134  << RHSExpr->getSourceRange();
11135 }
11136 
11137 /// Diagnose invalid arithmetic on a void pointer.
11139  Expr *Pointer) {
11140  S.Diag(Loc, S.getLangOpts().CPlusPlus
11141  ? diag::err_typecheck_pointer_arith_void_type
11142  : diag::ext_gnu_void_ptr)
11143  << 0 /* one pointer */ << Pointer->getSourceRange();
11144 }
11145 
11146 /// Diagnose invalid arithmetic on a null pointer.
11147 ///
11148 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11149 /// idiom, which we recognize as a GNU extension.
11150 ///
11152  Expr *Pointer, bool IsGNUIdiom) {
11153  if (IsGNUIdiom)
11154  S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11155  << Pointer->getSourceRange();
11156  else
11157  S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11158  << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11159 }
11160 
11161 /// Diagnose invalid subraction on a null pointer.
11162 ///
11164  Expr *Pointer, bool BothNull) {
11165  // Null - null is valid in C++ [expr.add]p7
11166  if (BothNull && S.getLangOpts().CPlusPlus)
11167  return;
11168 
11169  // Is this s a macro from a system header?
11171  return;
11172 
11173  S.DiagRuntimeBehavior(Loc, Pointer,
11174  S.PDiag(diag::warn_pointer_sub_null_ptr)
11175  << S.getLangOpts().CPlusPlus
11176  << Pointer->getSourceRange());
11177 }
11178 
11179 /// Diagnose invalid arithmetic on two function pointers.
11181  Expr *LHS, Expr *RHS) {
11182  assert(LHS->getType()->isAnyPointerType());
11183  assert(RHS->getType()->isAnyPointerType());
11184  S.Diag(Loc, S.getLangOpts().CPlusPlus
11185  ? diag::err_typecheck_pointer_arith_function_type
11186  : diag::ext_gnu_ptr_func_arith)
11187  << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11188  // We only show the second type if it differs from the first.
11190  RHS->getType())
11191  << RHS->getType()->getPointeeType()
11192  << LHS->getSourceRange() << RHS->getSourceRange();
11193 }
11194 
11195 /// Diagnose invalid arithmetic on a function pointer.
11197  Expr *Pointer) {
11198  assert(Pointer->getType()->isAnyPointerType());
11199  S.Diag(Loc, S.getLangOpts().CPlusPlus
11200  ? diag::err_typecheck_pointer_arith_function_type
11201  : diag::ext_gnu_ptr_func_arith)
11202  << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11203  << 0 /* one pointer, so only one type */
11204  << Pointer->getSourceRange();
11205 }
11206 
11207 /// Emit error if Operand is incomplete pointer type
11208 ///
11209 /// \returns True if pointer has incomplete type
11211  Expr *Operand) {
11212  QualType ResType = Operand->getType();
11213  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11214  ResType = ResAtomicType->getValueType();
11215 
11216  assert(ResType->isAnyPointerType() && !ResType->isDependentType());
11217  QualType PointeeTy = ResType->getPointeeType();
11218  return S.RequireCompleteSizedType(
11219  Loc, PointeeTy,
11220  diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11221  Operand->getSourceRange());
11222 }
11223 
11224 /// Check the validity of an arithmetic pointer operand.
11225 ///
11226 /// If the operand has pointer type, this code will check for pointer types
11227 /// which are invalid in arithmetic operations. These will be diagnosed
11228 /// appropriately, including whether or not the use is supported as an
11229 /// extension.
11230 ///
11231 /// \returns True when the operand is valid to use (even if as an extension).
11233  Expr *Operand) {
11234  QualType ResType = Operand->getType();
11235  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11236  ResType = ResAtomicType->getValueType();
11237 
11238  if (!ResType->isAnyPointerType()) return true;
11239 
11240  QualType PointeeTy = ResType->getPointeeType();
11241  if (PointeeTy->isVoidType()) {
11242  diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11243  return !S.getLangOpts().CPlusPlus;
11244  }
11245  if (PointeeTy->isFunctionType()) {
11246  diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11247  return !S.getLangOpts().CPlusPlus;
11248  }
11249 
11250  if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11251 
11252  return true;
11253 }
11254 
11255 /// Check the validity of a binary arithmetic operation w.r.t. pointer
11256 /// operands.
11257 ///
11258 /// This routine will diagnose any invalid arithmetic on pointer operands much
11259 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
11260 /// for emitting a single diagnostic even for operations where both LHS and RHS
11261 /// are (potentially problematic) pointers.
11262 ///
11263 /// \returns True when the operand is valid to use (even if as an extension).
11265  Expr *LHSExpr, Expr *RHSExpr) {
11266  bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11267  bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11268  if (!isLHSPointer && !isRHSPointer) return true;
11269 
11270  QualType LHSPointeeTy, RHSPointeeTy;
11271  if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11272  if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11273 
11274  // if both are pointers check if operation is valid wrt address spaces
11275  if (isLHSPointer && isRHSPointer) {
11276  if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
11277  S.Diag(Loc,
11278  diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11279  << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11280  << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11281  return false;
11282  }
11283  }
11284 
11285  // Check for arithmetic on pointers to incomplete types.
11286  bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11287  bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11288  if (isLHSVoidPtr || isRHSVoidPtr) {
11289  if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11290  else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11291  else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11292 
11293  return !S.getLangOpts().CPlusPlus;
11294  }
11295 
11296  bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11297  bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11298  if (isLHSFuncPtr || isRHSFuncPtr) {
11299  if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11300  else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11301  RHSExpr);
11302  else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11303 
11304  return !S.getLangOpts().CPlusPlus;
11305  }
11306 
11307  if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11308  return false;
11309  if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11310  return false;
11311 
11312  return true;
11313 }
11314 
11315 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11316 /// literal.
11317 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11318  Expr *LHSExpr, Expr *RHSExpr) {
11319  StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11320  Expr* IndexExpr = RHSExpr;
11321  if (!StrExpr) {
11322  StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11323  IndexExpr = LHSExpr;
11324  }
11325 
11326  bool IsStringPlusInt = StrExpr &&
11328  if (!IsStringPlusInt || IndexExpr->isValueDependent())
11329  return;
11330 
11331  SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11332  Self.Diag(OpLoc, diag::warn_string_plus_int)
11333  << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11334 
11335  // Only print a fixit for "str" + int, not for int + "str".
11336  if (IndexExpr == RHSExpr) {
11337  SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11338  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11339  << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11341  << FixItHint::CreateInsertion(EndLoc, "]");
11342  } else
11343  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11344 }
11345 
11346 /// Emit a warning when adding a char literal to a string.
11347 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11348  Expr *LHSExpr, Expr *RHSExpr) {
11349  const Expr *StringRefExpr = LHSExpr;
11350  const CharacterLiteral *CharExpr =
11351  dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11352 
11353  if (!CharExpr) {
11354  CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11355  StringRefExpr = RHSExpr;
11356  }
11357 
11358  if (!CharExpr || !StringRefExpr)
11359  return;
11360 
11361  const QualType StringType = StringRefExpr->getType();
11362 
11363  // Return if not a PointerType.
11364  if (!StringType->isAnyPointerType())
11365  return;
11366 
11367  // Return if not a CharacterType.
11368  if (!StringType->getPointeeType()->isAnyCharacterType())
11369  return;
11370 
11371  ASTContext &Ctx = Self.getASTContext();
11372  SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11373 
11374  const QualType CharType = CharExpr->getType();
11375  if (!CharType->isAnyCharacterType() &&
11376  CharType->isIntegerType() &&
11377  llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11378  Self.Diag(OpLoc, diag::warn_string_plus_char)
11379  << DiagRange << Ctx.CharTy;
11380  } else {
11381  Self.Diag(OpLoc, diag::warn_string_plus_char)
11382  << DiagRange << CharExpr->getType();
11383  }
11384 
11385  // Only print a fixit for str + char, not for char + str.
11386  if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11387  SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11388  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11389  << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11391  << FixItHint::CreateInsertion(EndLoc, "]");
11392  } else {
11393  Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11394  }
11395 }
11396 
11397 /// Emit error when two pointers are incompatible.
11399  Expr *LHSExpr, Expr *RHSExpr) {
11400  assert(LHSExpr->getType()->isAnyPointerType());
11401  assert(RHSExpr->getType()->isAnyPointerType());
11402  S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11403  << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11404  << RHSExpr->getSourceRange();
11405 }
11406 
11407 // C99 6.5.6
11410  QualType* CompLHSTy) {
11411  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11412 
11413  if (LHS.get()->getType()->isVectorType() ||
11414  RHS.get()->getType()->isVectorType()) {
11415  QualType compType =
11416  CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11417  /*AllowBothBool*/ getLangOpts().AltiVec,
11418  /*AllowBoolConversions*/ getLangOpts().ZVector,
11419  /*AllowBooleanOperation*/ false,
11420  /*ReportInvalid*/ true);
11421  if (CompLHSTy) *CompLHSTy = compType;
11422  return compType;
11423  }
11424 
11425  if (LHS.get()->getType()->isVLSTBuiltinType() ||
11426  RHS.get()->getType()->isVLSTBuiltinType()) {
11427  QualType compType =
11428  CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11429  if (CompLHSTy)
11430  *CompLHSTy = compType;
11431  return compType;
11432  }
11433 
11434  if (LHS.get()->getType()->isConstantMatrixType() ||
11435  RHS.get()->getType()->isConstantMatrixType()) {
11436  QualType compType =
11437  CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11438  if (CompLHSTy)
11439  *CompLHSTy = compType;
11440  return compType;
11441  }
11442 
11444  LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11445  if (LHS.isInvalid() || RHS.isInvalid())
11446  return QualType();
11447 
11448  // Diagnose "string literal" '+' int and string '+' "char literal".
11449  if (Opc == BO_Add) {
11450  diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11451  diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11452  }
11453 
11454  // handle the common case first (both operands are arithmetic).
11455  if (!compType.isNull() && compType->isArithmeticType()) {
11456  if (CompLHSTy) *CompLHSTy = compType;
11457  return compType;
11458  }
11459 
11460  // Type-checking. Ultimately the pointer's going to be in PExp;
11461  // note that we bias towards the LHS being the pointer.
11462  Expr *PExp = LHS.get(), *IExp = RHS.get();
11463 
11464  bool isObjCPointer;
11465  if (PExp->getType()->isPointerType()) {
11466  isObjCPointer = false;
11467  } else if (PExp->getType()->isObjCObjectPointerType()) {
11468  isObjCPointer = true;
11469  } else {
11470  std::swap(PExp, IExp);
11471  if (PExp->getType()->isPointerType()) {
11472  isObjCPointer = false;
11473  } else if (PExp->getType()->isObjCObjectPointerType()) {
11474  isObjCPointer = true;
11475  } else {
11476  return InvalidOperands(Loc, LHS, RHS);
11477  }
11478  }
11479  assert(PExp->getType()->isAnyPointerType());
11480 
11481  if (!IExp->getType()->isIntegerType())
11482  return InvalidOperands(Loc, LHS, RHS);
11483 
11484  // Adding to a null pointer results in undefined behavior.
11487  // In C++ adding zero to a null pointer is defined.
11488  Expr::EvalResult KnownVal;
11489  if (!getLangOpts().CPlusPlus ||
11490  (!IExp->isValueDependent() &&
11491  (!IExp->EvaluateAsInt(KnownVal, Context) ||
11492  KnownVal.Val.getInt() != 0))) {
11493  // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11495  Context, BO_Add, PExp, IExp);
11496  diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11497  }
11498  }
11499 
11500  if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11501  return QualType();
11502 
11503  if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11504  return QualType();
11505 
11506  // Check array bounds for pointer arithemtic
11507  CheckArrayAccess(PExp, IExp);
11508 
11509  if (CompLHSTy) {
11510  QualType LHSTy = Context.isPromotableBitField(LHS.get());
11511  if (LHSTy.isNull()) {
11512  LHSTy = LHS.get()->getType();
11513  if (Context.isPromotableIntegerType(LHSTy))
11514  LHSTy = Context.getPromotedIntegerType(LHSTy);
11515  }
11516  *CompLHSTy = LHSTy;
11517  }
11518 
11519  return PExp->getType();
11520 }
11521 
11522 // C99 6.5.6
11524  SourceLocation Loc,
11525  QualType* CompLHSTy) {
11526  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11527 
11528  if (LHS.get()->getType()->isVectorType() ||
11529  RHS.get()->getType()->isVectorType()) {
11530  QualType compType =
11531  CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11532  /*AllowBothBool*/ getLangOpts().AltiVec,
11533  /*AllowBoolConversions*/ getLangOpts().ZVector,
11534  /*AllowBooleanOperation*/ false,
11535  /*ReportInvalid*/ true);
11536  if (CompLHSTy) *CompLHSTy = compType;
11537  return compType;
11538  }
11539 
11540  if (LHS.get()->getType()->isVLSTBuiltinType() ||
11541  RHS.get()->getType()->isVLSTBuiltinType()) {
11542  QualType compType =
11543  CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11544  if (CompLHSTy)
11545  *CompLHSTy = compType;
11546  return compType;
11547  }
11548 
11549  if (LHS.get()->getType()->isConstantMatrixType() ||
11550  RHS.get()->getType()->isConstantMatrixType()) {
11551  QualType compType =
11552  CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11553  if (CompLHSTy)
11554  *CompLHSTy = compType;
11555  return compType;
11556  }
11557 
11559  LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11560  if (LHS.isInvalid() || RHS.isInvalid())
11561  return QualType();
11562 
11563  // Enforce type constraints: C99 6.5.6p3.
11564 
11565  // Handle the common case first (both operands are arithmetic).
11566  if (!compType.isNull() && compType->isArithmeticType()) {
11567  if (CompLHSTy) *CompLHSTy = compType;
11568  return compType;
11569  }
11570 
11571  // Either ptr - int or ptr - ptr.
11572  if (LHS.get()->getType()->isAnyPointerType()) {
11573  QualType lpointee = LHS.get()->getType()->getPointeeType();
11574 
11575  // Diagnose bad cases where we step over interface counts.
11576  if (LHS.get()->getType()->isObjCObjectPointerType() &&
11577  checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11578  return QualType();
11579 
11580  // The result type of a pointer-int computation is the pointer type.
11581  if (RHS.get()->getType()->isIntegerType()) {
11582  // Subtracting from a null pointer should produce a warning.
11583  // The last argument to the diagnose call says this doesn't match the
11584  // GNU int-to-pointer idiom.
11587  // In C++ adding zero to a null pointer is defined.
11588  Expr::EvalResult KnownVal;
11589  if (!getLangOpts().CPlusPlus ||
11590  (!RHS.get()->isValueDependent() &&
11591  (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11592  KnownVal.Val.getInt() != 0))) {
11593  diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11594  }
11595  }
11596 
11597  if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11598  return QualType();
11599 
11600  // Check array bounds for pointer arithemtic
11601  CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11602  /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11603 
11604  if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11605  return LHS.get()->getType();
11606  }
11607 
11608  // Handle pointer-pointer subtractions.
11609  if (const PointerType *RHSPTy
11610  = RHS.get()->getType()->getAs<PointerType>()) {
11611  QualType rpointee = RHSPTy->getPointeeType();
11612 
11613  if (getLangOpts().CPlusPlus) {
11614  // Pointee types must be the same: C++ [expr.add]
11615  if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11616  diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11617  }
11618  } else {
11619  // Pointee types must be compatible C99 6.5.6p3
11623  diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11624  return QualType();
11625  }
11626  }
11627 
11628  if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11629  LHS.get(), RHS.get()))
11630  return QualType();
11631 
11632  bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11634  bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11636 
11637  // Subtracting nullptr or from nullptr is suspect
11638  if (LHSIsNullPtr)
11639  diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11640  if (RHSIsNullPtr)
11641  diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11642 
11643  // The pointee type may have zero size. As an extension, a structure or
11644  // union may have zero size or an array may have zero length. In this
11645  // case subtraction does not make sense.
11646  if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11647  CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11648  if (ElementSize.isZero()) {
11649  Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11650  << rpointee.getUnqualifiedType()
11651  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11652  }
11653  }
11654 
11655  if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11656  return Context.getPointerDiffType();
11657  }
11658  }
11659 
11660  return InvalidOperands(Loc, LHS, RHS);
11661 }
11662 
11664  if (const EnumType *ET = T->getAs<EnumType>())
11665  return ET->getDecl()->isScoped();
11666  return false;
11667 }
11668 
11671  QualType LHSType) {
11672  // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11673  // so skip remaining warnings as we don't want to modify values within Sema.
11674  if (S.getLangOpts().OpenCL)
11675  return;
11676 
11677  // Check right/shifter operand
11678  Expr::EvalResult RHSResult;
11679  if (RHS.get()->isValueDependent() ||
11680  !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11681  return;
11682  llvm::APSInt Right = RHSResult.Val.getInt();
11683 
11684  if (Right.isNegative()) {
11685  S.DiagRuntimeBehavior(Loc, RHS.get(),
11686  S.PDiag(diag::warn_shift_negative)
11687  << RHS.get()->getSourceRange());
11688  return;
11689  }
11690 
11691  QualType LHSExprType = LHS.get()->getType();
11692  uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11693  if (LHSExprType->isBitIntType())
11694  LeftSize = S.Context.getIntWidth(LHSExprType);
11695  else if (LHSExprType->isFixedPointType()) {
11696  auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11697  LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11698  }
11699  llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11700  if (Right.uge(LeftBits)) {
11701  S.DiagRuntimeBehavior(Loc, RHS.get(),
11702  S.PDiag(diag::warn_shift_gt_typewidth)
11703  << RHS.get()->getSourceRange());
11704  return;
11705  }
11706 
11707  // FIXME: We probably need to handle fixed point types specially here.
11708  if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11709  return;
11710 
11711  // When left shifting an ICE which is signed, we can check for overflow which
11712  // according to C++ standards prior to C++2a has undefined behavior
11713  // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11714  // more than the maximum value representable in the result type, so never
11715  // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11716  // expression is still probably a bug.)
11717  Expr::EvalResult LHSResult;
11718  if (LHS.get()->isValueDependent() ||
11719  LHSType->hasUnsignedIntegerRepresentation() ||
11720  !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11721  return;
11722  llvm::APSInt Left = LHSResult.Val.getInt();
11723 
11724  // Don't warn if signed overflow is defined, then all the rest of the
11725  // diagnostics will not be triggered because the behavior is defined.
11726  // Also don't warn in C++20 mode (and newer), as signed left shifts
11727  // always wrap and never overflow.
11728  if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11729  return;
11730 
11731  // If LHS does not have a non-negative value then, the
11732  // behavior is undefined before C++2a. Warn about it.
11733  if (Left.isNegative()) {
11734  S.DiagRuntimeBehavior(Loc, LHS.get(),
11735  S.PDiag(diag::warn_shift_lhs_negative)
11736  << LHS.get()->getSourceRange());
11737  return;
11738  }
11739 
11740  llvm::APInt ResultBits =
11741  static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11742  if (LeftBits.uge(ResultBits))
11743  return;
11744  llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11745  Result = Result.shl(Right);
11746 
11747  // Print the bit representation of the signed integer as an unsigned
11748  // hexadecimal number.
11749  SmallString<40> HexResult;
11750  Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11751 
11752  // If we are only missing a sign bit, this is less likely to result in actual
11753  // bugs -- if the result is cast back to an unsigned type, it will have the
11754  // expected value. Thus we place this behind a different warning that can be
11755  // turned off separately if needed.
11756  if (LeftBits == ResultBits - 1) {
11757  S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11758  << HexResult << LHSType
11759  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11760  return;
11761  }
11762 
11763  S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11764  << HexResult.str() << Result.getMinSignedBits() << LHSType
11765  << Left.getBitWidth() << LHS.get()->getSourceRange()
11766  << RHS.get()->getSourceRange();
11767 }
11768 
11769 /// Return the resulting type when a vector is shifted
11770 /// by a scalar or vector shift amount.
11772  SourceLocation Loc, bool IsCompAssign) {
11773  // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11774  if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11775  !LHS.get()->getType()->isVectorType()) {
11776  S.Diag(Loc, diag::err_shift_rhs_only_vector)
11777  << RHS.get()->getType() << LHS.get()->getType()
11778  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11779  return QualType();
11780  }
11781 
11782  if (!IsCompAssign) {
11783  LHS = S.UsualUnaryConversions(LHS.get());
11784  if (LHS.isInvalid()) return QualType();
11785  }
11786 
11787  RHS = S.UsualUnaryConversions(RHS.get());
11788  if (RHS.isInvalid()) return QualType();
11789 
11790  QualType LHSType = LHS.get()->getType();
11791  // Note that LHS might be a scalar because the routine calls not only in
11792  // OpenCL case.
11793  const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11794  QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11795 
11796  // Note that RHS might not be a vector.
11797  QualType RHSType = RHS.get()->getType();
11798  const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11799  QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11800 
11801  // Do not allow shifts for boolean vectors.
11802  if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11803  (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11804  S.Diag(Loc, diag::err_typecheck_invalid_operands)
11805  << LHS.get()->getType() << RHS.get()->getType()
11806  << LHS.get()->getSourceRange();
11807  return QualType();
11808  }
11809 
11810  // The operands need to be integers.
11811  if (!LHSEleType->isIntegerType()) {
11812  S.Diag(Loc, diag::err_typecheck_expect_int)
11813  << LHS.get()->getType() << LHS.get()->getSourceRange();
11814  return QualType();
11815  }
11816 
11817  if (!RHSEleType->isIntegerType()) {
11818  S.Diag(Loc, diag::err_typecheck_expect_int)
11819  << RHS.get()->getType() << RHS.get()->getSourceRange();
11820  return QualType();
11821  }
11822 
11823  if (!LHSVecTy) {
11824  assert(RHSVecTy);
11825  if (IsCompAssign)
11826  return RHSType;
11827  if (LHSEleType != RHSEleType) {
11828  LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11829  LHSEleType = RHSEleType;
11830  }
11831  QualType VecTy =
11832  S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11833  LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11834  LHSType = VecTy;
11835  } else if (RHSVecTy) {
11836  // OpenCL v1.1 s6.3.j says that for vector types, the operators
11837  // are applied component-wise. So if RHS is a vector, then ensure
11838  // that the number of elements is the same as LHS...
11839  if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11840  S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11841  << LHS.get()->getType() << RHS.get()->getType()
11842  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11843  return QualType();
11844  }
11845  if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11846  const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11847  const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11848  if (LHSBT != RHSBT &&
11849  S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11850  S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11851  << LHS.get()->getType() << RHS.get()->getType()
11852  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11853  }
11854  }
11855  } else {
11856  // ...else expand RHS to match the number of elements in LHS.
11857  QualType VecTy =
11858  S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11859  RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11860  }
11861 
11862  return LHSType;
11863 }
11864 
11866  ExprResult &RHS, SourceLocation Loc,
11867  bool IsCompAssign) {
11868  if (!IsCompAssign) {
11869  LHS = S.UsualUnaryConversions(LHS.get());
11870  if (LHS.isInvalid())
11871  return QualType();
11872  }
11873 
11874  RHS = S.UsualUnaryConversions(RHS.get());
11875  if (RHS.isInvalid())
11876  return QualType();
11877 
11878  QualType LHSType = LHS.get()->getType();
11879  const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11880  QualType LHSEleType = LHSType->isVLSTBuiltinType()
11881  ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11882  : LHSType;
11883 
11884  // Note that RHS might not be a vector
11885  QualType RHSType = RHS.get()->getType();
11886  const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11887  QualType RHSEleType = RHSType->isVLSTBuiltinType()
11888  ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11889  : RHSType;
11890 
11891  if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11892  (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11893  S.Diag(Loc, diag::err_typecheck_invalid_operands)
11894  << LHSType << RHSType << LHS.get()->getSourceRange();
11895  return QualType();
11896  }
11897 
11898  if (!LHSEleType->isIntegerType()) {
11899  S.Diag(Loc, diag::err_typecheck_expect_int)
11900  << LHS.get()->getType() << LHS.get()->getSourceRange();
11901  return QualType();
11902  }
11903 
11904  if (!RHSEleType->isIntegerType()) {
11905  S.Diag(Loc, diag::err_typecheck_expect_int)
11906  << RHS.get()->getType() << RHS.get()->getSourceRange();
11907  return QualType();
11908  }
11909 
11910  if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
11911  (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11912  S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11913  S.Diag(Loc, diag::err_typecheck_invalid_operands)
11914  << LHSType << RHSType << LHS.get()->getSourceRange()
11915  << RHS.get()->getSourceRange();
11916  return QualType();
11917  }
11918 
11919  if (!LHSType->isVLSTBuiltinType()) {
11920  assert(RHSType->isVLSTBuiltinType());
11921  if (IsCompAssign)
11922  return RHSType;
11923  if (LHSEleType != RHSEleType) {
11924  LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11925  LHSEleType = RHSEleType;
11926  }
11927  const llvm::ElementCount VecSize =
11928  S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11929  QualType VecTy =
11930  S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11931  LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11932  LHSType = VecTy;
11933  } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) {
11934  if (S.Context.getTypeSize(RHSBuiltinTy) !=
11935  S.Context.getTypeSize(LHSBuiltinTy)) {
11936  S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11937  << LHSType << RHSType << LHS.get()->getSourceRange()
11938  << RHS.get()->getSourceRange();
11939  return QualType();
11940  }
11941  } else {
11942  const llvm::ElementCount VecSize =
11943  S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11944  if (LHSEleType != RHSEleType) {
11945  RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11946  RHSEleType = LHSEleType;
11947  }
11948  QualType VecTy =
11949  S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11950  RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11951  }
11952 
11953  return LHSType;
11954 }
11955 
11956 // C99 6.5.7
11959  bool IsCompAssign) {
11960  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11961 
11962  // Vector shifts promote their scalar inputs to vector type.
11963  if (LHS.get()->getType()->isVectorType() ||
11964  RHS.get()->getType()->isVectorType()) {
11965  if (LangOpts.ZVector) {
11966  // The shift operators for the z vector extensions work basically
11967  // like general shifts, except that neither the LHS nor the RHS is
11968  // allowed to be a "vector bool".
11969  if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11970  if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11971  return InvalidOperands(Loc, LHS, RHS);
11972  if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11973  if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11974  return InvalidOperands(Loc, LHS, RHS);
11975  }
11976  return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11977  }
11978 
11979  if (LHS.get()->getType()->isVLSTBuiltinType() ||
11980  RHS.get()->getType()->isVLSTBuiltinType())
11981  return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11982 
11983  // Shifts don't perform usual arithmetic conversions, they just do integer
11984  // promotions on each operand. C99 6.5.7p3
11985 
11986  // For the LHS, do usual unary conversions, but then reset them away
11987  // if this is a compound assignment.
11988  ExprResult OldLHS = LHS;
11989  LHS = UsualUnaryConversions(LHS.get());
11990  if (LHS.isInvalid())
11991  return QualType();
11992  QualType LHSType = LHS.get()->getType();
11993  if (IsCompAssign) LHS = OldLHS;
11994 
11995  // The RHS is simpler.
11996  RHS = UsualUnaryConversions(RHS.get());
11997  if (RHS.isInvalid())
11998  return QualType();
11999  QualType RHSType = RHS.get()->getType();
12000 
12001  // C99 6.5.7p2: Each of the operands shall have integer type.
12002  // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12003  if ((!LHSType->isFixedPointOrIntegerType() &&
12004  !LHSType->hasIntegerRepresentation()) ||
12005  !RHSType->hasIntegerRepresentation())
12006  return InvalidOperands(Loc, LHS, RHS);
12007 
12008  // C++0x: Don't allow scoped enums. FIXME: Use something better than
12009  // hasIntegerRepresentation() above instead of this.
12010  if (isScopedEnumerationType(LHSType) ||
12011  isScopedEnumerationType(RHSType)) {
12012  return InvalidOperands(Loc, LHS, RHS);
12013  }
12014  DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12015 
12016  // "The type of the result is that of the promoted left operand."
12017  return LHSType;
12018 }
12019 
12020 /// Diagnose bad pointer comparisons.
12022  ExprResult &LHS, ExprResult &RHS,
12023  bool IsError) {
12024  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12025  : diag::ext_typecheck_comparison_of_distinct_pointers)
12026  << LHS.get()->getType() << RHS.get()->getType()
12027  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12028 }
12029 
12030 /// Returns false if the pointers are converted to a composite type,
12031 /// true otherwise.
12033  ExprResult &LHS, ExprResult &RHS) {
12034  // C++ [expr.rel]p2:
12035  // [...] Pointer conversions (4.10) and qualification
12036  // conversions (4.4) are performed on pointer operands (or on
12037  // a pointer operand and a null pointer constant) to bring
12038  // them to their composite pointer type. [...]
12039  //
12040  // C++ [expr.eq]p1 uses the same notion for (in)equality
12041  // comparisons of pointers.
12042 
12043  QualType LHSType = LHS.get()->getType();
12044  QualType RHSType = RHS.get()->getType();
12045  assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12046  LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12047 
12048  QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12049  if (T.isNull()) {
12050  if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12051  (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12052  diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12053  else
12054  S.InvalidOperands(Loc, LHS, RHS);
12055  return true;
12056  }
12057 
12058  return false;
12059 }
12060 
12062  ExprResult &LHS,
12063  ExprResult &RHS,
12064  bool IsError) {
12065  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12066  : diag::ext_typecheck_comparison_of_fptr_to_void)
12067  << LHS.get()->getType() << RHS.get()->getType()
12068  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12069 }
12070 
12072  switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12073  case Stmt::ObjCArrayLiteralClass:
12074  case Stmt::ObjCDictionaryLiteralClass:
12075  case Stmt::ObjCStringLiteralClass:
12076  case Stmt::ObjCBoxedExprClass:
12077  return true;
12078  default:
12079  // Note that ObjCBoolLiteral is NOT an object literal!
12080  return false;
12081  }
12082 }
12083 
12084 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12085  const ObjCObjectPointerType *Type =
12086  LHS->getType()->getAs<ObjCObjectPointerType>();
12087 
12088  // If this is not actually an Objective-C object, bail out.
12089  if (!Type)
12090  return false;
12091 
12092  // Get the LHS object's interface type.
12093  QualType InterfaceType = Type->getPointeeType();
12094 
12095  // If the RHS isn't an Objective-C object, bail out.
12096  if (!RHS->getType()->isObjCObjectPointerType())
12097  return false;
12098 
12099  // Try to find the -isEqual: method.
12100  Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
12101  ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
12102  InterfaceType,
12103  /*IsInstance=*/true);
12104  if (!Method) {
12105  if (Type->isObjCIdType()) {
12106  // For 'id', just check the global pool.
12107  Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
12108  /*receiverId=*/true);
12109  } else {
12110  // Check protocols.
12111  Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
12112  /*IsInstance=*/true);
12113  }
12114  }
12115 
12116  if (!Method)
12117  return false;
12118 
12119  QualType T = Method->parameters()[0]->getType();
12120  if (!T->isObjCObjectPointerType())
12121  return false;
12122 
12123  QualType R = Method->getReturnType();
12124  if (!R->isScalarType())
12125  return false;
12126 
12127  return true;
12128 }
12129 
12131  FromE = FromE->IgnoreParenImpCasts();
12132  switch (FromE->getStmtClass()) {
12133  default:
12134  break;
12135  case Stmt::ObjCStringLiteralClass:
12136  // "string literal"
12137  return LK_String;
12138  case Stmt::ObjCArrayLiteralClass:
12139  // "array literal"
12140  return LK_Array;
12141  case Stmt::ObjCDictionaryLiteralClass:
12142  // "dictionary literal"
12143  return LK_Dictionary;
12144  case Stmt::BlockExprClass:
12145  return LK_Block;
12146  case Stmt::ObjCBoxedExprClass: {
12147  Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
12148  switch (Inner->getStmtClass()) {
12149  case Stmt::IntegerLiteralClass:
12150  case Stmt::FloatingLiteralClass:
12151  case Stmt::CharacterLiteralClass:
12152  case Stmt::ObjCBoolLiteralExprClass:
12153  case Stmt::CXXBoolLiteralExprClass:
12154  // "numeric literal"
12155  return LK_Numeric;
12156  case Stmt::ImplicitCastExprClass: {
12157  CastKind CK = cast<CastExpr>(Inner)->getCastKind();
12158  // Boolean literals can be represented by implicit casts.
12159  if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
12160  return LK_Numeric;
12161  break;
12162  }
12163  default:
12164  break;
12165  }
12166  return LK_Boxed;
12167  }
12168  }
12169  return LK_None;
12170 }
12171 
12173  ExprResult &LHS, ExprResult &RHS,
12175  Expr *Literal;
12176  Expr *Other;
12177  if (isObjCObjectLiteral(LHS)) {
12178  Literal = LHS.get();
12179  Other = RHS.get();
12180  } else {
12181  Literal = RHS.get();
12182  Other = LHS.get();
12183  }
12184 
12185  // Don't warn on comparisons against nil.
12186  Other = Other->IgnoreParenCasts();
12187  if (Other->isNullPointerConstant(S.getASTContext(),
12189  return;
12190 
12191  // This should be kept in sync with warn_objc_literal_comparison.
12192  // LK_String should always be after the other literals, since it has its own
12193  // warning flag.
12195  assert(LiteralKind != Sema::LK_Block);
12196  if (LiteralKind == Sema::LK_None) {
12197  llvm_unreachable("Unknown Objective-C object literal kind");
12198  }
12199 
12200  if (LiteralKind == Sema::LK_String)
12201  S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12202  << Literal->getSourceRange();
12203  else
12204  S.Diag(Loc, diag::warn_objc_literal_comparison)
12205  << LiteralKind << Literal->getSourceRange();
12206 
12207  if (BinaryOperator::isEqualityOp(Opc) &&
12208  hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12209  SourceLocation Start = LHS.get()->getBeginLoc();
12211  CharSourceRange OpRange =
12213 
12214  S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12215  << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12216  << FixItHint::CreateReplacement(OpRange, " isEqual:")
12218  }
12219 }
12220 
12221 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12223  ExprResult &RHS, SourceLocation Loc,
12224  BinaryOperatorKind Opc) {
12225  // Check that left hand side is !something.
12226  UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12227  if (!UO || UO->getOpcode() != UO_LNot) return;
12228 
12229  // Only check if the right hand side is non-bool arithmetic type.
12230  if (RHS.get()->isKnownToHaveBooleanValue()) return;
12231 
12232  // Make sure that the something in !something is not bool.
12233  Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12234  if (SubExpr->isKnownToHaveBooleanValue()) return;
12235 
12236  // Emit warning.
12237  bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12238  S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12239  << Loc << IsBitwiseOp;
12240 
12241  // First note suggest !(x < y)
12242  SourceLocation FirstOpen = SubExpr->getBeginLoc();
12243  SourceLocation FirstClose = RHS.get()->getEndLoc();
12244  FirstClose = S.getLocForEndOfToken(FirstClose);
12245  if (FirstClose.isInvalid())
12246  FirstOpen = SourceLocation();
12247  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12248  << IsBitwiseOp
12249  << FixItHint::CreateInsertion(FirstOpen, "(")
12250  << FixItHint::CreateInsertion(FirstClose, ")");
12251 
12252  // Second note suggests (!x) < y
12253  SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12254  SourceLocation SecondClose = LHS.get()->getEndLoc();
12255  SecondClose = S.getLocForEndOfToken(SecondClose);
12256  if (SecondClose.isInvalid())
12257  SecondOpen = SourceLocation();
12258  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12259  << FixItHint::CreateInsertion(SecondOpen, "(")
12260  << FixItHint::CreateInsertion(SecondClose, ")");
12261 }
12262 
12263 // Returns true if E refers to a non-weak array.
12264 static bool checkForArray(const Expr *E) {
12265  const ValueDecl *D = nullptr;
12266  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12267  D = DR->getDecl();
12268  } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12269  if (Mem->isImplicitAccess())
12270  D = Mem->getMemberDecl();
12271  }
12272  if (!D)
12273  return false;
12274  return D->getType()->isArrayType() && !D->isWeak();
12275 }
12276 
12277 /// Diagnose some forms of syntactically-obvious tautological comparison.
12279  Expr *LHS, Expr *RHS,
12280  BinaryOperatorKind Opc) {
12281  Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12282  Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12283 
12284  QualType LHSType = LHS->getType();
12285  QualType RHSType = RHS->getType();
12286  if (LHSType->hasFloatingRepresentation() ||
12287  (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12289  return;
12290 
12291  // Comparisons between two array types are ill-formed for operator<=>, so
12292  // we shouldn't emit any additional warnings about it.
12293  if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12294  return;
12295 
12296  // For non-floating point types, check for self-comparisons of the form
12297  // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12298  // often indicate logic errors in the program.
12299  //
12300  // NOTE: Don't warn about comparison expressions resulting from macro
12301  // expansion. Also don't warn about comparisons which are only self
12302  // comparisons within a template instantiation. The warnings should catch
12303  // obvious cases in the definition of the template anyways. The idea is to
12304  // warn when the typed comparison operator will always evaluate to the same
12305  // result.
12306 
12307  // Used for indexing into %select in warn_comparison_always
12308  enum {
12309  AlwaysConstant,
12310  AlwaysTrue,
12311  AlwaysFalse,
12312  AlwaysEqual, // std::strong_ordering::equal from operator<=>
12313  };
12314 
12315  // C++2a [depr.array.comp]:
12316  // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12317  // operands of array type are deprecated.
12318  if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12319  RHSStripped->getType()->isArrayType()) {
12320  S.Diag(Loc, diag::warn_depr_array_comparison)
12321  << LHS->getSourceRange() << RHS->getSourceRange()
12322  << LHSStripped->getType() << RHSStripped->getType();
12323  // Carry on to produce the tautological comparison warning, if this
12324  // expression is potentially-evaluated, we can resolve the array to a
12325  // non-weak declaration, and so on.
12326  }
12327 
12328  if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12329  if (Expr::isSameComparisonOperand(LHS, RHS)) {
12330  unsigned Result;
12331  switch (Opc) {
12332  case BO_EQ:
12333  case BO_LE:
12334  case BO_GE:
12335  Result = AlwaysTrue;
12336  break;
12337  case BO_NE:
12338  case BO_LT:
12339  case BO_GT:
12340  Result = AlwaysFalse;
12341  break;
12342  case BO_Cmp:
12343  Result = AlwaysEqual;
12344  break;
12345  default:
12346  Result = AlwaysConstant;
12347  break;
12348  }
12349  S.DiagRuntimeBehavior(Loc, nullptr,
12350  S.PDiag(diag::warn_comparison_always)
12351  << 0 /*self-comparison*/
12352  << Result);
12353  } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12354  // What is it always going to evaluate to?
12355  unsigned Result;
12356  switch (Opc) {
12357  case BO_EQ: // e.g. array1 == array2
12358  Result = AlwaysFalse;
12359  break;
12360  case BO_NE: // e.g. array1 != array2
12361  Result = AlwaysTrue;
12362  break;
12363  default: // e.g. array1 <= array2
12364  // The best we can say is 'a constant'
12365  Result = AlwaysConstant;
12366  break;
12367  }
12368  S.DiagRuntimeBehavior(Loc, nullptr,
12369  S.PDiag(diag::warn_comparison_always)
12370  << 1 /*array comparison*/
12371  << Result);
12372  }
12373  }
12374 
12375  if (isa<CastExpr>(LHSStripped))
12376  LHSStripped = LHSStripped->IgnoreParenCasts();
12377  if (isa<CastExpr>(RHSStripped))
12378  RHSStripped = RHSStripped->IgnoreParenCasts();
12379 
12380  // Warn about comparisons against a string constant (unless the other
12381  // operand is null); the user probably wants string comparison function.
12382  Expr *LiteralString = nullptr;
12383  Expr *LiteralStringStripped = nullptr;
12384  if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12385  !RHSStripped->isNullPointerConstant(S.Context,
12387  LiteralString = LHS;
12388  LiteralStringStripped = LHSStripped;
12389  } else if ((isa<StringLiteral>(RHSStripped) ||
12390  isa<ObjCEncodeExpr>(RHSStripped)) &&
12391  !LHSStripped->isNullPointerConstant(S.Context,
12393  LiteralString = RHS;
12394  LiteralStringStripped = RHSStripped;
12395  }
12396 
12397  if (LiteralString) {
12398  S.DiagRuntimeBehavior(Loc, nullptr,
12399  S.PDiag(diag::warn_stringcompare)
12400  << isa<ObjCEncodeExpr>(LiteralStringStripped)
12401  << LiteralString->getSourceRange());
12402  }
12403 }
12404 
12406  switch (CK) {
12407  default: {
12408 #ifndef NDEBUG
12409  llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12410  << "\n";
12411 #endif
12412  llvm_unreachable("unhandled cast kind");
12413  }
12414  case CK_UserDefinedConversion:
12415  return ICK_Identity;
12416  case CK_LValueToRValue:
12417  return ICK_Lvalue_To_Rvalue;
12418  case CK_ArrayToPointerDecay:
12419  return ICK_Array_To_Pointer;
12420  case CK_FunctionToPointerDecay:
12421  return ICK_Function_To_Pointer;
12422  case CK_IntegralCast:
12423  return ICK_Integral_Conversion;
12424  case CK_FloatingCast:
12425  return ICK_Floating_Conversion;
12426  case CK_IntegralToFloating:
12427  case CK_FloatingToIntegral:
12428  return ICK_Floating_Integral;
12429  case CK_IntegralComplexCast:
12430  case CK_FloatingComplexCast:
12431  case CK_FloatingComplexToIntegralComplex:
12432  case CK_IntegralComplexToFloatingComplex:
12433  return ICK_Complex_Conversion;
12434  case CK_FloatingComplexToReal:
12435  case CK_FloatingRealToComplex:
12436  case CK_IntegralComplexToReal:
12437  case CK_IntegralRealToComplex:
12438  return ICK_Complex_Real;
12439  }
12440 }
12441 
12443  QualType FromType,
12444  SourceLocation Loc) {
12445  // Check for a narrowing implicit conversion.
12448  SCS.setToType(0, FromType);
12449  SCS.setToType(1, ToType);
12450  if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12451  SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12452 
12453  APValue PreNarrowingValue;
12454  QualType PreNarrowingType;
12455  switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12456  PreNarrowingType,
12457  /*IgnoreFloatToIntegralConversion*/ true)) {
12459  // Implicit conversion to a narrower type, but the expression is
12460  // value-dependent so we can't tell whether it's actually narrowing.
12461  case NK_Not_Narrowing:
12462  return false;
12463 
12464  case NK_Constant_Narrowing:
12465  // Implicit conversion to a narrower type, and the value is not a constant
12466  // expression.
12467  S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12468  << /*Constant*/ 1
12469  << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12470  return true;
12471 
12472  case NK_Variable_Narrowing:
12473  // Implicit conversion to a narrower type, and the value is not a constant
12474  // expression.
12475  case NK_Type_Narrowing:
12476  S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12477  << /*Constant*/ 0 << FromType << ToType;
12478  // TODO: It's not a constant expression, but what if the user intended it
12479  // to be? Can we produce notes to help them figure out why it isn't?
12480  return true;
12481  }
12482  llvm_unreachable("unhandled case in switch");
12483 }
12484 
12486  ExprResult &LHS,
12487  ExprResult &RHS,
12488  SourceLocation Loc) {
12489  QualType LHSType = LHS.get()->getType();
12490  QualType RHSType = RHS.get()->getType();
12491  // Dig out the original argument type and expression before implicit casts
12492  // were applied. These are the types/expressions we need to check the
12493  // [expr.spaceship] requirements against.
12494  ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12495  ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12496  QualType LHSStrippedType = LHSStripped.get()->getType();
12497  QualType RHSStrippedType = RHSStripped.get()->getType();
12498 
12499  // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12500  // other is not, the program is ill-formed.
12501  if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12502  S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12503  return QualType();
12504  }
12505 
12506  // FIXME: Consider combining this with checkEnumArithmeticConversions.
12507  int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12508  RHSStrippedType->isEnumeralType();
12509  if (NumEnumArgs == 1) {
12510  bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12511  QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12512  if (OtherTy->hasFloatingRepresentation()) {
12513  S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12514  return QualType();
12515  }
12516  }
12517  if (NumEnumArgs == 2) {
12518  // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12519  // type E, the operator yields the result of converting the operands
12520  // to the underlying type of E and applying <=> to the converted operands.
12521  if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12522  S.InvalidOperands(Loc, LHS, RHS);
12523  return QualType();
12524  }
12525  QualType IntType =
12526  LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12527  assert(IntType->isArithmeticType());
12528 
12529  // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12530  // promote the boolean type, and all other promotable integer types, to
12531  // avoid this.
12532  if (S.Context.isPromotableIntegerType(IntType))
12533  IntType = S.Context.getPromotedIntegerType(IntType);
12534 
12535  LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12536  RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12537  LHSType = RHSType = IntType;
12538  }
12539 
12540  // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12541  // usual arithmetic conversions are applied to the operands.
12542  QualType Type =
12544  if (LHS.isInvalid() || RHS.isInvalid())
12545  return QualType();
12546  if (Type.isNull())
12547  return S.InvalidOperands(Loc, LHS, RHS);
12548 
12549  std::optional<ComparisonCategoryType> CCT =
12551  if (!CCT)
12552  return S.InvalidOperands(Loc, LHS, RHS);
12553 
12554  bool HasNarrowing = checkThreeWayNarrowingConversion(
12555  S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12556  HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12557  RHS.get()->getBeginLoc());
12558  if (HasNarrowing)
12559  return QualType();
12560 
12561  assert(!Type.isNull() && "composite type for <=> has not been set");
12562 
12563  return S.CheckComparisonCategoryType(
12565 }
12566 
12568  ExprResult &RHS,
12569  SourceLocation Loc,
12570  BinaryOperatorKind Opc) {
12571  if (Opc == BO_Cmp)
12572  return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12573 
12574  // C99 6.5.8p3 / C99 6.5.9p4
12575  QualType Type =
12577  if (LHS.isInvalid() || RHS.isInvalid())
12578  return QualType();
12579  if (Type.isNull())
12580  return S.InvalidOperands(Loc, LHS, RHS);
12581  assert(Type->isArithmeticType() || Type->isEnumeralType());
12582 
12584  return S.InvalidOperands(Loc, LHS, RHS);
12585 
12586  // Check for comparisons of floating point operands using != and ==.
12588  S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12589 
12590  // The result of comparisons is 'bool' in C++, 'int' in C.
12591  return S.Context.getLogicalOperationType();
12592 }
12593 
12595  if (!NullE.get()->getType()->isAnyPointerType())
12596  return;
12597  int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12598  if (!E.get()->getType()->isAnyPointerType() &&
12602  if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12603  if (CL->getValue() == 0)
12604  Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12605  << NullValue
12607  NullValue ? "NULL" : "(void *)0");
12608  } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12609  TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12611  if (T == Context.CharTy)
12612  Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12613  << NullValue
12615  NullValue ? "NULL" : "(void *)0");
12616  }
12617  }
12618 }
12619 
12620 // C99 6.5.8, C++ [expr.rel]
12622  SourceLocation Loc,
12623  BinaryOperatorKind Opc) {
12624  bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12625  bool IsThreeWay = Opc == BO_Cmp;
12626  bool IsOrdered = IsRelational || IsThreeWay;
12627  auto IsAnyPointerType = [](ExprResult E) {
12628  QualType Ty = E.get()->getType();
12629  return Ty->isPointerType() || Ty->isMemberPointerType();
12630  };
12631 
12632  // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12633  // type, array-to-pointer, ..., conversions are performed on both operands to
12634  // bring them to their composite type.
12635  // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12636  // any type-related checks.
12637  if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12639  if (LHS.isInvalid())
12640  return QualType();
12642  if (RHS.isInvalid())
12643  return QualType();
12644  } else {
12645  LHS = DefaultLvalueConversion(LHS.get());
12646  if (LHS.isInvalid())
12647  return QualType();
12648  RHS = DefaultLvalueConversion(RHS.get());
12649  if (RHS.isInvalid())
12650  return QualType();
12651  }
12652 
12653  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12657  }
12658 
12659  // Handle vector comparisons separately.
12660  if (LHS.get()->getType()->isVectorType() ||
12661  RHS.get()->getType()->isVectorType())
12662  return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12663 
12664  if (LHS.get()->getType()->isVLSTBuiltinType() ||
12665  RHS.get()->getType()->isVLSTBuiltinType())
12666  return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12667 
12668  diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12669  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12670 
12671  QualType LHSType = LHS.get()->getType();
12672  QualType RHSType = RHS.get()->getType();
12673  if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12674  (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12675  return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12676 
12677  const Expr::NullPointerConstantKind LHSNullKind =
12679  const Expr::NullPointerConstantKind RHSNullKind =
12681  bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12682  bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12683 
12684  auto computeResultTy = [&]() {
12685  if (Opc != BO_Cmp)
12687  assert(getLangOpts().CPlusPlus);
12688  assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12689 
12690  QualType CompositeTy = LHS.get()->getType();
12691  assert(!CompositeTy->isReferenceType());
12692 
12693  std::optional<ComparisonCategoryType> CCT =
12695  if (!CCT)
12696  return InvalidOperands(Loc, LHS, RHS);
12697 
12698  if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12699  // P0946R0: Comparisons between a null pointer constant and an object
12700  // pointer result in std::strong_equality, which is ill-formed under
12701  // P1959R0.
12702  Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12703  << (LHSIsNull ? LHS.get()->getSourceRange()
12704  : RHS.get()->getSourceRange());
12705  return QualType();
12706  }
12707 
12710  };
12711 
12712  if (!IsOrdered && LHSIsNull != RHSIsNull) {
12713  bool IsEquality = Opc == BO_EQ;
12714  if (RHSIsNull)
12715  DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12716  RHS.get()->getSourceRange());
12717  else
12718  DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12719  LHS.get()->getSourceRange());
12720  }
12721 
12722  if (IsOrdered && LHSType->isFunctionPointerType() &&
12723  RHSType->isFunctionPointerType()) {
12724  // Valid unless a relational comparison of function pointers
12725  bool IsError = Opc == BO_Cmp;
12726  auto DiagID =
12727  IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12728  : getLangOpts().CPlusPlus
12729  ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12730  : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12731  Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12732  << RHS.get()->getSourceRange();
12733  if (IsError)
12734  return QualType();
12735  }
12736 
12737  if ((LHSType->isIntegerType() && !LHSIsNull) ||
12738  (RHSType->isIntegerType() && !RHSIsNull)) {
12739  // Skip normal pointer conversion checks in this case; we have better
12740  // diagnostics for this below.
12741  } else if (getLangOpts().CPlusPlus) {
12742  // Equality comparison of a function pointer to a void pointer is invalid,
12743  // but we allow it as an extension.
12744  // FIXME: If we really want to allow this, should it be part of composite
12745  // pointer type computation so it works in conditionals too?
12746  if (!IsOrdered &&
12747  ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12748  (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12749  // This is a gcc extension compatibility comparison.
12750  // In a SFINAE context, we treat this as a hard error to maintain
12751  // conformance with the C++ standard.
12753  *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12754 
12755  if (isSFINAEContext())
12756  return QualType();
12757 
12758  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12759  return computeResultTy();
12760  }
12761 
12762  // C++ [expr.eq]p2:
12763  // If at least one operand is a pointer [...] bring them to their
12764  // composite pointer type.
12765  // C++ [expr.spaceship]p6
12766  // If at least one of the operands is of pointer type, [...] bring them
12767  // to their composite pointer type.
12768  // C++ [expr.rel]p2:
12769  // If both operands are pointers, [...] bring them to their composite
12770  // pointer type.
12771  // For <=>, the only valid non-pointer types are arrays and functions, and
12772  // we already decayed those, so this is really the same as the relational
12773  // comparison rule.
12774  if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12775  (IsOrdered ? 2 : 1) &&
12776  (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12777  RHSType->isObjCObjectPointerType()))) {
12778  if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12779  return QualType();
12780  return computeResultTy();
12781  }
12782  } else if (LHSType->isPointerType() &&
12783  RHSType->isPointerType()) { // C99 6.5.8p2
12784  // All of the following pointer-related warnings are GCC extensions, except
12785  // when handling null pointer constants.
12786  QualType LCanPointeeTy =
12787  LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12788  QualType RCanPointeeTy =
12789  RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12790 
12791  // C99 6.5.9p2 and C99 6.5.8p2
12792  if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12793  RCanPointeeTy.getUnqualifiedType())) {
12794  if (IsRelational) {
12795  // Pointers both need to point to complete or incomplete types
12796  if ((LCanPointeeTy->isIncompleteType() !=
12797  RCanPointeeTy->isIncompleteType()) &&
12798  !getLangOpts().C11) {
12799  Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12800  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12801  << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12802  << RCanPointeeTy->isIncompleteType();
12803  }
12804  }
12805  } else if (!IsRelational &&
12806  (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12807  // Valid unless comparison between non-null pointer and function pointer
12808  if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12809  && !LHSIsNull && !RHSIsNull)
12810  diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12811  /*isError*/false);
12812  } else {
12813  // Invalid
12814  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12815  }
12816  if (LCanPointeeTy != RCanPointeeTy) {
12817  // Treat NULL constant as a special case in OpenCL.
12818  if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12819  if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12820  Diag(Loc,
12821  diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12822  << LHSType << RHSType << 0 /* comparison */
12823  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12824  }
12825  }
12826  LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12827  LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12828  CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12829  : CK_BitCast;
12830  if (LHSIsNull && !RHSIsNull)
12831  LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12832  else
12833  RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12834  }
12835  return computeResultTy();
12836  }
12837 
12838 
12839  // C++ [expr.eq]p4:
12840  // Two operands of type std::nullptr_t or one operand of type
12841  // std::nullptr_t and the other a null pointer constant compare
12842  // equal.
12843  // C2x 6.5.9p5:
12844  // If both operands have type nullptr_t or one operand has type nullptr_t
12845  // and the other is a null pointer constant, they compare equal.
12846  if (!IsOrdered && LHSIsNull && RHSIsNull) {
12847  if (LHSType->isNullPtrType()) {
12848  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12849  return computeResultTy();
12850  }
12851  if (RHSType->isNullPtrType()) {
12852  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12853  return computeResultTy();
12854  }
12855  }
12856 
12857  if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12858  // C2x 6.5.9p6:
12859  // Otherwise, at least one operand is a pointer. If one is a pointer and
12860  // the other is a null pointer constant, the null pointer constant is
12861  // converted to the type of the pointer.
12862  if (LHSIsNull && RHSType->isPointerType()) {
12863  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12864  return computeResultTy();
12865  }
12866  if (RHSIsNull && LHSType->isPointerType()) {
12867  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12868  return computeResultTy();
12869  }
12870  }
12871 
12872  // Comparison of Objective-C pointers and block pointers against nullptr_t.
12873  // These aren't covered by the composite pointer type rules.
12874  if (!IsOrdered && RHSType->isNullPtrType() &&
12875  (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12876  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12877  return computeResultTy();
12878  }
12879  if (!IsOrdered && LHSType->isNullPtrType() &&
12880  (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12881  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12882  return computeResultTy();
12883  }
12884 
12885  if (getLangOpts().CPlusPlus) {
12886  if (IsRelational &&
12887  ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12888  (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12889  // HACK: Relational comparison of nullptr_t against a pointer type is
12890  // invalid per DR583, but we allow it within std::less<> and friends,
12891  // since otherwise common uses of it break.
12892  // FIXME: Consider removing this hack once LWG fixes std::less<> and
12893  // friends to have std::nullptr_t overload candidates.
12894  DeclContext *DC = CurContext;
12895  if (isa<FunctionDecl>(DC))
12896  DC = DC->getParent();
12897  if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12898  if (CTSD->isInStdNamespace() &&
12899  llvm::StringSwitch<bool>(CTSD->getName())
12900  .Cases("less", "less_equal", "greater", "greater_equal", true)
12901  .Default(false)) {
12902  if (RHSType->isNullPtrType())
12903  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12904  else
12905  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12906  return computeResultTy();
12907  }
12908  }
12909  }
12910 
12911  // C++ [expr.eq]p2:
12912  // If at least one operand is a pointer to member, [...] bring them to
12913  // their composite pointer type.
12914  if (!IsOrdered &&
12915  (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12916  if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12917  return QualType();
12918  else
12919  return computeResultTy();
12920  }
12921  }
12922 
12923  // Handle block pointer types.
12924  if (!IsOrdered && LHSType->isBlockPointerType() &&
12925  RHSType->isBlockPointerType()) {
12926  QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12927  QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12928 
12929  if (!LHSIsNull && !RHSIsNull &&
12930  !Context.typesAreCompatible(lpointee, rpointee)) {
12931  Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12932  << LHSType << RHSType << LHS.get()->getSourceRange()
12933  << RHS.get()->getSourceRange();
12934  }
12935  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12936  return computeResultTy();
12937  }
12938 
12939  // Allow block pointers to be compared with null pointer constants.
12940  if (!IsOrdered
12941  && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12942  || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12943  if (!LHSIsNull && !RHSIsNull) {
12944  if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12945  ->getPointeeType()->isVoidType())
12946  || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12947  ->getPointeeType()->isVoidType())))
12948  Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12949  << LHSType << RHSType << LHS.get()->getSourceRange()
12950  << RHS.get()->getSourceRange();
12951  }
12952  if (LHSIsNull && !RHSIsNull)
12953  LHS = ImpCastExprToType(LHS.get(), RHSType,
12954  RHSType->isPointerType() ? CK_BitCast
12955  : CK_AnyPointerToBlockPointerCast);
12956  else
12957  RHS = ImpCastExprToType(RHS.get(), LHSType,
12958  LHSType->isPointerType() ? CK_BitCast
12959  : CK_AnyPointerToBlockPointerCast);
12960  return computeResultTy();
12961  }
12962 
12963  if (LHSType->isObjCObjectPointerType() ||
12964  RHSType->isObjCObjectPointerType()) {
12965  const PointerType *LPT = LHSType->getAs<PointerType>();
12966  const PointerType *RPT = RHSType->getAs<PointerType>();
12967  if (LPT || RPT) {
12968  bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12969  bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12970 
12971  if (!LPtrToVoid && !RPtrToVoid &&
12972  !Context.typesAreCompatible(LHSType, RHSType)) {
12973  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12974  /*isError*/false);
12975  }
12976  // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12977  // the RHS, but we have test coverage for this behavior.
12978  // FIXME: Consider using convertPointersToCompositeType in C++.
12979  if (LHSIsNull && !RHSIsNull) {
12980  Expr *E = LHS.get();
12981  if (getLangOpts().ObjCAutoRefCount)
12982  CheckObjCConversion(SourceRange(), RHSType, E,
12984  LHS = ImpCastExprToType(E, RHSType,
12985  RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12986  }
12987  else {
12988  Expr *E = RHS.get();
12989  if (getLangOpts().ObjCAutoRefCount)
12991  /*Diagnose=*/true,
12992  /*DiagnoseCFAudited=*/false, Opc);
12993  RHS = ImpCastExprToType(E, LHSType,
12994  LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12995  }
12996  return computeResultTy();
12997  }
12998  if (LHSType->isObjCObjectPointerType() &&
12999  RHSType->isObjCObjectPointerType()) {
13000  if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13001  diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13002  /*isError*/false);
13003  if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
13004  diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13005 
13006  if (LHSIsNull && !RHSIsNull)
13007  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13008  else
13009  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13010  return computeResultTy();
13011  }
13012 
13013  if (!IsOrdered && LHSType->isBlockPointerType() &&
13015  LHS = ImpCastExprToType(LHS.get(), RHSType,
13016  CK_BlockPointerToObjCPointerCast);
13017  return computeResultTy();
13018  } else if (!IsOrdered &&
13020  RHSType->isBlockPointerType()) {
13021  RHS = ImpCastExprToType(RHS.get(), LHSType,
13022  CK_BlockPointerToObjCPointerCast);
13023  return computeResultTy();
13024  }
13025  }
13026  if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13027  (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13028  unsigned DiagID = 0;
13029  bool isError = false;
13030  if (LangOpts.DebuggerSupport) {
13031  // Under a debugger, allow the comparison of pointers to integers,
13032  // since users tend to want to compare addresses.
13033  } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13034  (RHSIsNull && RHSType->isIntegerType())) {
13035  if (IsOrdered) {
13036  isError = getLangOpts().CPlusPlus;
13037  DiagID =
13038  isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13039  : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13040  }
13041  } else if (getLangOpts().CPlusPlus) {
13042  DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13043  isError = true;
13044  } else if (IsOrdered)
13045  DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13046  else
13047  DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13048 
13049  if (DiagID) {
13050  Diag(Loc, DiagID)
13051  << LHSType << RHSType << LHS.get()->getSourceRange()
13052  << RHS.get()->getSourceRange();
13053  if (isError)
13054  return QualType();
13055  }
13056 
13057  if (LHSType->isIntegerType())
13058  LHS = ImpCastExprToType(LHS.get(), RHSType,
13059  LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13060  else
13061  RHS = ImpCastExprToType(RHS.get(), LHSType,
13062  RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13063  return computeResultTy();
13064  }
13065 
13066  // Handle block pointers.
13067  if (!IsOrdered && RHSIsNull
13068  && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13069  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13070  return computeResultTy();
13071  }
13072  if (!IsOrdered && LHSIsNull
13073  && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13074  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13075  return computeResultTy();
13076  }
13077 
13078  if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13079  if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13080  return computeResultTy();
13081  }
13082 
13083  if (LHSType->isQueueT() && RHSType->isQueueT()) {
13084  return computeResultTy();
13085  }
13086 
13087  if (LHSIsNull && RHSType->isQueueT()) {
13088  LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13089  return computeResultTy();
13090  }
13091 
13092  if (LHSType->isQueueT() && RHSIsNull) {
13093  RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13094  return computeResultTy();
13095  }
13096  }
13097 
13098  return InvalidOperands(Loc, LHS, RHS);
13099 }
13100 
13101 // Return a signed ext_vector_type that is of identical size and number of
13102 // elements. For floating point vectors, return an integer type of identical
13103 // size and number of elements. In the non ext_vector_type case, search from
13104 // the largest type to the smallest type to avoid cases where long long == long,
13105 // where long gets picked over long long.
13107  const VectorType *VTy = V->castAs<VectorType>();
13108  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13109 
13110  if (isa<ExtVectorType>(VTy)) {
13111  if (VTy->isExtVectorBoolType())
13113  if (TypeSize == Context.getTypeSize(Context.CharTy))
13115  if (TypeSize == Context.getTypeSize(Context.ShortTy))
13117  if (TypeSize == Context.getTypeSize(Context.IntTy))
13119  if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13121  if (TypeSize == Context.getTypeSize(Context.LongTy))
13123  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13124  "Unhandled vector element size in vector compare");
13126  }
13127 
13128  if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13131  if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13134  if (TypeSize == Context.getTypeSize(Context.LongTy))
13137  if (TypeSize == Context.getTypeSize(Context.IntTy))
13140  if (TypeSize == Context.getTypeSize(Context.ShortTy))
13143  assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13144  "Unhandled vector element size in vector compare");
13147 }
13148 
13150  const BuiltinType *VTy = V->castAs<BuiltinType>();
13151  assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13152 
13153  const QualType ETy = V->getSveEltType(Context);
13154  const auto TypeSize = Context.getTypeSize(ETy);
13155 
13156  const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13157  const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13158  return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13159 }
13160 
13161 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
13162 /// operates on extended vector types. Instead of producing an IntTy result,
13163 /// like a scalar comparison, a vector comparison produces a vector of integer
13164 /// types.
13166  SourceLocation Loc,
13167  BinaryOperatorKind Opc) {
13168  if (Opc == BO_Cmp) {
13169  Diag(Loc, diag::err_three_way_vector_comparison);
13170  return QualType();
13171  }
13172 
13173  // Check to make sure we're operating on vectors of the same type and width,
13174  // Allowing one side to be a scalar of element type.
13175  QualType vType =
13176  CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13177  /*AllowBothBool*/ true,
13178  /*AllowBoolConversions*/ getLangOpts().ZVector,
13179  /*AllowBooleanOperation*/ true,
13180  /*ReportInvalid*/ true);
13181  if (vType.isNull())
13182  return vType;
13183 
13184  QualType LHSType = LHS.get()->getType();
13185 
13186  // Determine the return type of a vector compare. By default clang will return
13187  // a scalar for all vector compares except vector bool and vector pixel.
13188  // With the gcc compiler we will always return a vector type and with the xl
13189  // compiler we will always return a scalar type. This switch allows choosing
13190  // which behavior is prefered.
13191  if (getLangOpts().AltiVec) {
13192  switch (getLangOpts().getAltivecSrcCompat()) {
13194  // If AltiVec, the comparison results in a numeric type, i.e.
13195  // bool for C++, int for C
13196  if (vType->castAs<VectorType>()->getVectorKind() ==
13199  else
13200  Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13201  break;
13203  // For GCC we always return the vector type.
13204  break;
13207  break;
13208  }
13209  }
13210 
13211  // For non-floating point types, check for self-comparisons of the form
13212  // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13213  // often indicate logic errors in the program.
13214  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13215 
13216  // Check for comparisons of floating point operands using != and ==.
13217  if (LHSType->hasFloatingRepresentation()) {
13218  assert(RHS.get()->getType()->hasFloatingRepresentation());
13219  CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13220  }
13221 
13222  // Return a signed type for the vector.
13223  return GetSignedVectorType(vType);
13224 }
13225 
13227  ExprResult &RHS,
13228  SourceLocation Loc,
13229  BinaryOperatorKind Opc) {
13230  if (Opc == BO_Cmp) {
13231  Diag(Loc, diag::err_three_way_vector_comparison);
13232  return QualType();
13233  }
13234 
13235  // Check to make sure we're operating on vectors of the same type and width,
13236  // Allowing one side to be a scalar of element type.
13238  LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
13239 
13240  if (vType.isNull())
13241  return vType;
13242 
13243  QualType LHSType = LHS.get()->getType();
13244 
13245  // For non-floating point types, check for self-comparisons of the form
13246  // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13247  // often indicate logic errors in the program.
13248  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13249 
13250  // Check for comparisons of floating point operands using != and ==.
13251  if (LHSType->hasFloatingRepresentation()) {
13252  assert(RHS.get()->getType()->hasFloatingRepresentation());
13253  CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13254  }
13255 
13256  const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13257  const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13258 
13259  if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13260  RHSBuiltinTy->isSVEBool())
13261  return LHSType;
13262 
13263  // Return a signed type for the vector.
13264  return GetSignedSizelessVectorType(vType);
13265 }
13266 
13267 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13268  const ExprResult &XorRHS,
13269  const SourceLocation Loc) {
13270  // Do not diagnose macros.
13271  if (Loc.isMacroID())
13272  return;
13273 
13274  // Do not diagnose if both LHS and RHS are macros.
13275  if (XorLHS.get()->getExprLoc().isMacroID() &&
13276  XorRHS.get()->getExprLoc().isMacroID())
13277  return;
13278 
13279  bool Negative = false;
13280  bool ExplicitPlus = false;
13281  const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13282  const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13283 
13284  if (!LHSInt)
13285  return;
13286  if (!RHSInt) {
13287  // Check negative literals.
13288  if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13289  UnaryOperatorKind Opc = UO->getOpcode();
13290  if (Opc != UO_Minus && Opc != UO_Plus)
13291  return;
13292  RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13293  if (!RHSInt)
13294  return;
13295  Negative = (Opc == UO_Minus);
13296  ExplicitPlus = !Negative;
13297  } else {
13298  return;
13299  }
13300  }
13301 
13302  const llvm::APInt &LeftSideValue = LHSInt->getValue();
13303  llvm::APInt RightSideValue = RHSInt->getValue();
13304  if (LeftSideValue != 2 && LeftSideValue != 10)
13305  return;
13306 
13307  if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13308  return;
13309 
13311  LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13312  llvm::StringRef ExprStr =
13313  Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
13314 
13315  CharSourceRange XorRange =
13317  llvm::StringRef XorStr =
13319  // Do not diagnose if xor keyword/macro is used.
13320  if (XorStr == "xor")
13321  return;
13322 
13324  CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13325  S.getSourceManager(), S.getLangOpts()));
13327  CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13328  S.getSourceManager(), S.getLangOpts()));
13329 
13330  if (Negative) {
13331  RightSideValue = -RightSideValue;
13332  RHSStr = "-" + RHSStr;
13333  } else if (ExplicitPlus) {
13334  RHSStr = "+" + RHSStr;
13335  }
13336 
13337  StringRef LHSStrRef = LHSStr;
13338  StringRef RHSStrRef = RHSStr;
13339  // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13340  // literals.
13341  if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
13342  RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
13343  LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
13344  RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
13345  (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
13346  (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
13347  LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13348  return;
13349 
13350  bool SuggestXor =
13351  S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13352  const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13353  int64_t RightSideIntValue = RightSideValue.getSExtValue();
13354  if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13355  std::string SuggestedExpr = "1 << " + RHSStr;
13356  bool Overflow = false;
13357  llvm::APInt One = (LeftSideValue - 1);
13358  llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13359  if (Overflow) {
13360  if (RightSideIntValue < 64)
13361  S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13362  << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13363  << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13364  else if (RightSideIntValue == 64)
13365  S.Diag(Loc, diag::warn_xor_used_as_pow)
13366  << ExprStr << toString(XorValue, 10, true);
13367  else
13368  return;
13369  } else {
13370  S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13371  << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13372  << toString(PowValue, 10, true)
13374  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13375  }
13376 
13377  S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13378  << ("0x2 ^ " + RHSStr) << SuggestXor;
13379  } else if (LeftSideValue == 10) {
13380  std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13381  S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13382  << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13383  << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13384  S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13385  << ("0xA ^ " + RHSStr) << SuggestXor;
13386  }
13387 }
13388 
13390  SourceLocation Loc) {
13391  // Ensure that either both operands are of the same vector type, or
13392  // one operand is of a vector type and the other is of its element type.
13393  QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13394  /*AllowBothBool*/ true,
13395  /*AllowBoolConversions*/ false,
13396  /*AllowBooleanOperation*/ false,
13397  /*ReportInvalid*/ false);
13398  if (vType.isNull())
13399  return InvalidOperands(Loc, LHS, RHS);
13400  if (getLangOpts().OpenCL &&
13401  getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13402  vType->hasFloatingRepresentation())
13403  return InvalidOperands(Loc, LHS, RHS);
13404  // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13405  // usage of the logical operators && and || with vectors in C. This
13406  // check could be notionally dropped.
13407  if (!getLangOpts().CPlusPlus &&
13408  !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13409  return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13410 
13411  return GetSignedVectorType(LHS.get()->getType());
13412 }
13413 
13415  SourceLocation Loc,
13416  bool IsCompAssign) {
13417  if (!IsCompAssign) {
13419  if (LHS.isInvalid())
13420  return QualType();
13421  }
13423  if (RHS.isInvalid())
13424  return QualType();
13425 
13426  // For conversion purposes, we ignore any qualifiers.
13427  // For example, "const float" and "float" are equivalent.
13428  QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13429  QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13430 
13431  const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13432  const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13433  assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13434 
13435  if (Context.hasSameType(LHSType, RHSType))
13436  return Context.getCommonSugaredType(LHSType, RHSType);
13437 
13438  // Type conversion may change LHS/RHS. Keep copies to the original results, in
13439  // case we have to return InvalidOperands.
13440  ExprResult OriginalLHS = LHS;
13441  ExprResult OriginalRHS = RHS;
13442  if (LHSMatType && !RHSMatType) {
13443  RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13444  if (!RHS.isInvalid())
13445  return LHSType;
13446 
13447  return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13448  }
13449 
13450  if (!LHSMatType && RHSMatType) {
13451  LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13452  if (!LHS.isInvalid())
13453  return RHSType;
13454  return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13455  }
13456 
13457  return InvalidOperands(Loc, LHS, RHS);
13458 }
13459 
13461  SourceLocation Loc,
13462  bool IsCompAssign) {
13463  if (!IsCompAssign) {
13465  if (LHS.isInvalid())
13466  return QualType();
13467  }
13469  if (RHS.isInvalid())
13470  return QualType();
13471 
13472  auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13473  auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13474  assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13475 
13476  if (LHSMatType && RHSMatType) {
13477  if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13478  return InvalidOperands(Loc, LHS, RHS);
13479 
13480  if (Context.hasSameType(LHSMatType, RHSMatType))
13482  LHS.get()->getType().getUnqualifiedType(),
13483  RHS.get()->getType().getUnqualifiedType());
13484 
13485  QualType LHSELTy = LHSMatType->getElementType(),
13486  RHSELTy = RHSMatType->getElementType();
13487  if (!Context.hasSameType(LHSELTy, RHSELTy))
13488  return InvalidOperands(Loc, LHS, RHS);
13489 
13491  Context.getCommonSugaredType(LHSELTy, RHSELTy),
13492  LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13493  }
13494  return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13495 }
13496 
13498  switch (Opc) {
13499  default:
13500  return false;
13501  case BO_And:
13502  case BO_AndAssign:
13503  case BO_Or:
13504  case BO_OrAssign:
13505  case BO_Xor:
13506  case BO_XorAssign:
13507  return true;
13508  }
13509 }
13510 
13512  SourceLocation Loc,
13513  BinaryOperatorKind Opc) {
13514  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13515 
13516  bool IsCompAssign =
13517  Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13518 
13519  bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13520 
13521  if (LHS.get()->getType()->isVectorType() ||
13522  RHS.get()->getType()->isVectorType()) {
13523  if (LHS.get()->getType()->hasIntegerRepresentation() &&
13524  RHS.get()->getType()->hasIntegerRepresentation())
13525  return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13526  /*AllowBothBool*/ true,
13527  /*AllowBoolConversions*/ getLangOpts().ZVector,
13528  /*AllowBooleanOperation*/ LegalBoolVecOperator,
13529  /*ReportInvalid*/ true);
13530  return InvalidOperands(Loc, LHS, RHS);
13531  }
13532 
13533  if (LHS.get()->getType()->isVLSTBuiltinType() ||
13534  RHS.get()->getType()->isVLSTBuiltinType()) {
13535  if (LHS.get()->getType()->hasIntegerRepresentation() &&
13536  RHS.get()->getType()->hasIntegerRepresentation())
13537  return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13538  ACK_BitwiseOp);
13539  return InvalidOperands(Loc, LHS, RHS);
13540  }
13541 
13542  if (LHS.get()->getType()->isVLSTBuiltinType() ||
13543  RHS.get()->getType()->isVLSTBuiltinType()) {
13544  if (LHS.get()->getType()->hasIntegerRepresentation() &&
13545  RHS.get()->getType()->hasIntegerRepresentation())
13546  return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13547  ACK_BitwiseOp);
13548  return InvalidOperands(Loc, LHS, RHS);
13549  }
13550 
13551  if (Opc == BO_And)
13552  diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13553 
13554  if (LHS.get()->getType()->hasFloatingRepresentation() ||
13556  return InvalidOperands(Loc, LHS, RHS);
13557 
13558  ExprResult LHSResult = LHS, RHSResult = RHS;
13560  LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13561  if (LHSResult.isInvalid() || RHSResult.isInvalid())
13562  return QualType();
13563  LHS = LHSResult.get();
13564  RHS = RHSResult.get();
13565 
13566  if (Opc == BO_Xor)
13567  diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13568 
13569  if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13570  return compType;
13571  return InvalidOperands(Loc, LHS, RHS);
13572 }
13573 
13574 // C99 6.5.[13,14]
13576  SourceLocation Loc,
13577  BinaryOperatorKind Opc) {
13578  // Check vector operands differently.
13579  if (LHS.get()->getType()->isVectorType() ||
13580  RHS.get()->getType()->isVectorType())
13581  return CheckVectorLogicalOperands(LHS, RHS, Loc);
13582 
13583  bool EnumConstantInBoolContext = false;
13584  for (const ExprResult &HS : {LHS, RHS}) {
13585  if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13586  const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13587  if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13588  EnumConstantInBoolContext = true;
13589  }
13590  }
13591 
13592  if (EnumConstantInBoolContext)
13593  Diag(Loc, diag::warn_enum_constant_in_bool_context);
13594 
13595  // Diagnose cases where the user write a logical and/or but probably meant a
13596  // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13597  // is a constant.
13598  if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13599  !LHS.get()->getType()->isBooleanType() &&
13600  RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13601  // Don't warn in macros or template instantiations.
13602  !Loc.isMacroID() && !inTemplateInstantiation()) {
13603  // If the RHS can be constant folded, and if it constant folds to something
13604  // that isn't 0 or 1 (which indicate a potential logical operation that
13605  // happened to fold to true/false) then warn.
13606  // Parens on the RHS are ignored.
13607  Expr::EvalResult EVResult;
13608  if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13609  llvm::APSInt Result = EVResult.Val.getInt();
13610  if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13611  !RHS.get()->getExprLoc().isMacroID()) ||
13612  (Result != 0 && Result != 1)) {
13613  Diag(Loc, diag::warn_logical_instead_of_bitwise)
13614  << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13615  // Suggest replacing the logical operator with the bitwise version
13616  Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13617  << (Opc == BO_LAnd ? "&" : "|")
13619  SourceRange(Loc, getLocForEndOfToken(Loc)),
13620  Opc == BO_LAnd ? "&" : "|");
13621  if (Opc == BO_LAnd)
13622  // Suggest replacing "Foo() && kNonZero" with "Foo()"
13623  Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13626  RHS.get()->getEndLoc()));
13627  }
13628  }
13629  }
13630 
13631  if (!Context.getLangOpts().CPlusPlus) {
13632  // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13633  // not operate on the built-in scalar and vector float types.
13634  if (Context.getLangOpts().OpenCL &&
13635  Context.getLangOpts().OpenCLVersion < 120) {
13636  if (LHS.get()->getType()->isFloatingType() ||
13637  RHS.get()->getType()->isFloatingType())
13638  return InvalidOperands(Loc, LHS, RHS);
13639  }
13640 
13641  LHS = UsualUnaryConversions(LHS.get());
13642  if (LHS.isInvalid())
13643  return QualType();
13644 
13645  RHS = UsualUnaryConversions(RHS.get());
13646  if (RHS.isInvalid())
13647  return QualType();
13648 
13649  if (!LHS.get()->getType()->isScalarType() ||
13650  !RHS.get()->getType()->isScalarType())
13651  return InvalidOperands(Loc, LHS, RHS);
13652 
13653  return Context.IntTy;
13654  }
13655 
13656  // The following is safe because we only use this method for
13657  // non-overloadable operands.
13658 
13659  // C++ [expr.log.and]p1
13660  // C++ [expr.log.or]p1
13661  // The operands are both contextually converted to type bool.
13663  if (LHSRes.isInvalid())
13664  return InvalidOperands(Loc, LHS, RHS);
13665  LHS = LHSRes;
13666 
13668  if (RHSRes.isInvalid())
13669  return InvalidOperands(Loc, LHS, RHS);
13670  RHS = RHSRes;
13671 
13672  // C++ [expr.log.and]p2
13673  // C++ [expr.log.or]p2
13674  // The result is a bool.
13675  return Context.BoolTy;
13676 }
13677 
13678 static bool IsReadonlyMessage(Expr *E, Sema &S) {
13679  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13680  if (!ME) return false;
13681  if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13682  ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13684  if (!Base) return false;
13685  return Base->getMethodDecl() != nullptr;
13686 }
13687 
13688 /// Is the given expression (which must be 'const') a reference to a
13689 /// variable which was originally non-const, but which has become
13690 /// 'const' due to being captured within a block?
13693  assert(E->isLValue() && E->getType().isConstQualified());
13694  E = E->IgnoreParens();
13695 
13696  // Must be a reference to a declaration from an enclosing scope.
13697  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13698  if (!DRE) return NCCK_None;
13699  if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13700 
13701  // The declaration must be a variable which is not declared 'const'.
13702  VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13703  if (!var) return NCCK_None;
13704  if (var->getType().isConstQualified()) return NCCK_None;
13705  assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13706 
13707  // Decide whether the first capture was for a block or a lambda.
13708  DeclContext *DC = S.CurContext, *Prev = nullptr;
13709  // Decide whether the first capture was for a block or a lambda.
13710  while (DC) {
13711  // For init-capture, it is possible that the variable belongs to the
13712  // template pattern of the current context.
13713  if (auto *FD = dyn_cast<FunctionDecl>(DC))
13714  if (var->isInitCapture() &&
13715  FD->getTemplateInstantiationPattern() == var->getDeclContext())
13716  break;
13717  if (DC == var->getDeclContext())
13718  break;
13719  Prev = DC;
13720  DC = DC->getParent();
13721  }
13722  // Unless we have an init-capture, we've gone one step too far.
13723  if (!var->isInitCapture())
13724  DC = Prev;
13725  return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13726 }
13727 
13728 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13729  Ty = Ty.getNonReferenceType();
13730  if (IsDereference && Ty->isPointerType())
13731  Ty = Ty->getPointeeType();
13732  return !Ty.isConstQualified();
13733 }
13734 
13735 // Update err_typecheck_assign_const and note_typecheck_assign_const
13736 // when this enum is changed.
13737 enum {
13743  ConstUnknown, // Keep as last element
13744 };
13745 
13746 /// Emit the "read-only variable not assignable" error and print notes to give
13747 /// more information about why the variable is not assignable, such as pointing
13748 /// to the declaration of a const variable, showing that a method is const, or
13749 /// that the function is returning a const reference.
13750 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13751  SourceLocation Loc) {
13752  SourceRange ExprRange = E->getSourceRange();
13753 
13754  // Only emit one error on the first const found. All other consts will emit
13755  // a note to the error.
13756  bool DiagnosticEmitted = false;
13757 
13758  // Track if the current expression is the result of a dereference, and if the
13759  // next checked expression is the result of a dereference.
13760  bool IsDereference = false;
13761  bool NextIsDereference = false;
13762 
13763  // Loop to process MemberExpr chains.
13764  while (true) {
13765  IsDereference = NextIsDereference;
13766 
13767  E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13768  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13769  NextIsDereference = ME->isArrow();
13770  const ValueDecl *VD = ME->getMemberDecl();
13771  if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13772  // Mutable fields can be modified even if the class is const.
13773  if (Field->isMutable()) {
13774  assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13775  break;
13776  }
13777 
13778  if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13779  if (!DiagnosticEmitted) {
13780  S.Diag(Loc, diag::err_typecheck_assign_const)
13781  << ExprRange << ConstMember << false /*static*/ << Field
13782  << Field->getType();
13783  DiagnosticEmitted = true;
13784  }
13785  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13786  << ConstMember << false /*static*/ << Field << Field->getType()
13787  << Field->getSourceRange();
13788  }
13789  E = ME->getBase();
13790  continue;
13791  } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13792  if (VDecl->getType().isConstQualified()) {
13793  if (!DiagnosticEmitted) {
13794  S.Diag(Loc, diag::err_typecheck_assign_const)
13795  << ExprRange << ConstMember << true /*static*/ << VDecl
13796  << VDecl->getType();
13797  DiagnosticEmitted = true;
13798  }
13799  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13800  << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13801  << VDecl->getSourceRange();
13802  }
13803  // Static fields do not inherit constness from parents.
13804  break;
13805  }
13806  break; // End MemberExpr
13807  } else if (const ArraySubscriptExpr *ASE =
13808  dyn_cast<ArraySubscriptExpr>(E)) {
13809  E = ASE->getBase()->IgnoreParenImpCasts();
13810  continue;
13811  } else if (const ExtVectorElementExpr *EVE =
13812  dyn_cast<ExtVectorElementExpr>(E)) {
13813  E = EVE->getBase()->IgnoreParenImpCasts();
13814  continue;
13815  }
13816  break;
13817  }
13818 
13819  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13820  // Function calls
13821  const FunctionDecl *FD = CE->getDirectCallee();
13822  if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13823  if (!DiagnosticEmitted) {
13824  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13825  << ConstFunction << FD;
13826  DiagnosticEmitted = true;
13827  }
13829  diag::note_typecheck_assign_const)
13830  << ConstFunction << FD << FD->getReturnType()
13831  << FD->getReturnTypeSourceRange();
13832  }
13833  } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13834  // Point to variable declaration.
13835  if (const ValueDecl *VD = DRE->getDecl()) {
13836  if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13837  if (!DiagnosticEmitted) {
13838  S.Diag(Loc, diag::err_typecheck_assign_const)
13839  << ExprRange << ConstVariable << VD << VD->getType();
13840  DiagnosticEmitted = true;
13841  }
13842  S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13843  << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13844  }
13845  }
13846  } else if (isa<CXXThisExpr>(E)) {
13847  if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13848  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13849  if (MD->isConst()) {
13850  if (!DiagnosticEmitted) {
13851  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13852  << ConstMethod << MD;
13853  DiagnosticEmitted = true;
13854  }
13855  S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13856  << ConstMethod << MD << MD->getSourceRange();
13857  }
13858  }
13859  }
13860  }
13861 
13862  if (DiagnosticEmitted)
13863  return;
13864 
13865  // Can't determine a more specific message, so display the generic error.
13866  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13867 }
13868 
13873 };
13874 
13875 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13876  const RecordType *Ty,
13877  SourceLocation Loc, SourceRange Range,
13878  OriginalExprKind OEK,
13879  bool &DiagnosticEmitted) {
13880  std::vector<const RecordType *> RecordTypeList;
13881  RecordTypeList.push_back(Ty);
13882  unsigned NextToCheckIndex = 0;
13883  // We walk the record hierarchy breadth-first to ensure that we print
13884  // diagnostics in field nesting order.
13885  while (RecordTypeList.size() > NextToCheckIndex) {
13886  bool IsNested = NextToCheckIndex > 0;
13887  for (const FieldDecl *Field :
13888  RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13889  // First, check every field for constness.
13890  QualType FieldTy = Field->getType();
13891  if (FieldTy.isConstQualified()) {
13892  if (!DiagnosticEmitted) {
13893  S.Diag(Loc, diag::err_typecheck_assign_const)
13894  << Range << NestedConstMember << OEK << VD
13895  << IsNested << Field;
13896  DiagnosticEmitted = true;
13897  }
13898  S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13899  << NestedConstMember << IsNested << Field
13900  << FieldTy << Field->getSourceRange();
13901  }
13902 
13903  // Then we append it to the list to check next in order.
13904  FieldTy = FieldTy.getCanonicalType();
13905  if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13906  if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13907  RecordTypeList.push_back(FieldRecTy);
13908  }
13909  }
13910  ++NextToCheckIndex;
13911  }
13912 }
13913 
13914 /// Emit an error for the case where a record we are trying to assign to has a
13915 /// const-qualified field somewhere in its hierarchy.
13916 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13917  SourceLocation Loc) {
13918  QualType Ty = E->getType();
13919  assert(Ty->isRecordType() && "lvalue was not record?");
13920  SourceRange Range = E->getSourceRange();
13921  const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13922  bool DiagEmitted = false;
13923 
13924  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13925  DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13926  Range, OEK_Member, DiagEmitted);
13927  else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13928  DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13929  Range, OEK_Variable, DiagEmitted);
13930  else
13931  DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13932  Range, OEK_LValue, DiagEmitted);
13933  if (!DiagEmitted)
13934  DiagnoseConstAssignment(S, E, Loc);
13935 }
13936 
13937 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13938 /// emit an error and return true. If so, return false.
13940  assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13941 
13943 
13944  SourceLocation OrigLoc = Loc;
13946  &Loc);
13947  if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13949  if (IsLV == Expr::MLV_Valid)
13950  return false;
13951 
13952  unsigned DiagID = 0;
13953  bool NeedType = false;
13954  switch (IsLV) { // C99 6.5.16p2
13956  // Use a specialized diagnostic when we're assigning to an object
13957  // from an enclosing function or block.
13959  if (NCCK == NCCK_Block)
13960  DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13961  else
13962  DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13963  break;
13964  }
13965 
13966  // In ARC, use some specialized diagnostics for occasions where we
13967  // infer 'const'. These are always pseudo-strong variables.
13968  if (S.getLangOpts().ObjCAutoRefCount) {
13969  DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13970  if (declRef && isa<VarDecl>(declRef->getDecl())) {
13971  VarDecl *var = cast<VarDecl>(declRef->getDecl());
13972 
13973  // Use the normal diagnostic if it's pseudo-__strong but the
13974  // user actually wrote 'const'.
13975  if (var->isARCPseudoStrong() &&
13976  (!var->getTypeSourceInfo() ||
13977  !var->getTypeSourceInfo()->getType().isConstQualified())) {
13978  // There are three pseudo-strong cases:
13979  // - self
13980  ObjCMethodDecl *method = S.getCurMethodDecl();
13981  if (method && var == method->getSelfDecl()) {
13982  DiagID = method->isClassMethod()
13983  ? diag::err_typecheck_arc_assign_self_class_method
13984  : diag::err_typecheck_arc_assign_self;
13985 
13986  // - Objective-C externally_retained attribute.
13987  } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13988  isa<ParmVarDecl>(var)) {
13989  DiagID = diag::err_typecheck_arc_assign_externally_retained;
13990 
13991  // - fast enumeration variables
13992  } else {
13993  DiagID = diag::err_typecheck_arr_assign_enumeration;
13994  }
13995 
13996  SourceRange Assign;
13997  if (Loc != OrigLoc)
13998  Assign = SourceRange(OrigLoc, OrigLoc);
13999  S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14000  // We need to preserve the AST regardless, so migration tool
14001  // can do its job.
14002  return false;
14003  }
14004  }
14005  }
14006 
14007  // If none of the special cases above are triggered, then this is a
14008  // simple const assignment.
14009  if (DiagID == 0) {
14010  DiagnoseConstAssignment(S, E, Loc);
14011  return true;
14012  }
14013 
14014  break;
14016  DiagnoseConstAssignment(S, E, Loc);
14017  return true;
14019  DiagnoseRecursiveConstFields(S, E, Loc);
14020  return true;
14021  case Expr::MLV_ArrayType:
14023  DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14024  NeedType = true;
14025  break;
14027  DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14028  NeedType = true;
14029  break;
14030  case Expr::MLV_LValueCast:
14031  DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14032  break;
14033  case Expr::MLV_Valid:
14034  llvm_unreachable("did not take early return for MLV_Valid");
14038  DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14039  break;
14042  return S.RequireCompleteType(Loc, E->getType(),
14043  diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14045  DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14046  break;
14048  llvm_unreachable("readonly properties should be processed differently");
14050  DiagID = diag::err_readonly_message_assignment;
14051  break;
14053  DiagID = diag::err_no_subobject_property_setting;
14054  break;
14055  }
14056 
14057  SourceRange Assign;
14058  if (Loc != OrigLoc)
14059  Assign = SourceRange(OrigLoc, OrigLoc);
14060  if (NeedType)
14061  S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14062  else
14063  S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14064  return true;
14065 }
14066 
14067 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14068  SourceLocation Loc,
14069  Sema &Sema) {
14071  return;
14072  if (Sema.isUnevaluatedContext())
14073  return;
14074  if (Loc.isInvalid() || Loc.isMacroID())
14075  return;
14076  if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14077  return;
14078 
14079  // C / C++ fields
14080  MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14081  MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14082  if (ML && MR) {
14083  if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14084  return;
14085  const ValueDecl *LHSDecl =
14086  cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
14087  const ValueDecl *RHSDecl =
14088  cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
14089  if (LHSDecl != RHSDecl)
14090  return;
14091  if (LHSDecl->getType().isVolatileQualified())
14092  return;
14093  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14094  if (RefTy->getPointeeType().isVolatileQualified())
14095  return;
14096 
14097  Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14098  }
14099 
14100  // Objective-C instance variables
14101  ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14102  ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14103  if (OL && OR && OL->getDecl() == OR->getDecl()) {
14104  DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14105  DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14106  if (RL && RR && RL->getDecl() == RR->getDecl())
14107  Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14108  }
14109 }
14110 
14111 // C99 6.5.16.1
14113  SourceLocation Loc,
14114  QualType CompoundType,
14115  BinaryOperatorKind Opc) {
14116  assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14117 
14118  // Verify that LHS is a modifiable lvalue, and emit error if not.
14119  if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14120  return QualType();
14121 
14122  QualType LHSType = LHSExpr->getType();
14123  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14124  CompoundType;
14125  // OpenCL v1.2 s6.1.1.1 p2:
14126  // The half data type can only be used to declare a pointer to a buffer that
14127  // contains half values
14128  if (getLangOpts().OpenCL &&
14129  !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14130  LHSType->isHalfType()) {
14131  Diag(Loc, diag::err_opencl_half_load_store) << 1
14132  << LHSType.getUnqualifiedType();
14133  return QualType();
14134  }
14135 
14136  AssignConvertType ConvTy;
14137  if (CompoundType.isNull()) {
14138  Expr *RHSCheck = RHS.get();
14139 
14140  CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14141 
14142  QualType LHSTy(LHSType);
14143  ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14144  if (RHS.isInvalid())
14145  return QualType();
14146  // Special case of NSObject attributes on c-style pointer types.
14147  if (ConvTy == IncompatiblePointer &&
14148  ((Context.isObjCNSObjectType(LHSType) &&
14149  RHSType->isObjCObjectPointerType()) ||
14150  (Context.isObjCNSObjectType(RHSType) &&
14151  LHSType->isObjCObjectPointerType())))
14152  ConvTy = Compatible;
14153 
14154  if (ConvTy == Compatible &&
14155  LHSType->isObjCObjectType())
14156  Diag(Loc, diag::err_objc_object_assignment)
14157  << LHSType;
14158 
14159  // If the RHS is a unary plus or minus, check to see if they = and + are
14160  // right next to each other. If so, the user may have typo'd "x =+ 4"
14161  // instead of "x += 4".
14162  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14163  RHSCheck = ICE->getSubExpr();
14164  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14165  if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14166  Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14167  // Only if the two operators are exactly adjacent.
14168  Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14169  // And there is a space or other character before the subexpr of the
14170  // unary +/-. We don't want to warn on "x=-1".
14171  Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14172  UO->getSubExpr()->getBeginLoc().isFileID()) {
14173  Diag(Loc, diag::warn_not_compound_assign)
14174  << (UO->getOpcode() == UO_Plus ? "+" : "-")
14175  << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14176  }
14177  }
14178 
14179  if (ConvTy == Compatible) {
14180  if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14181  // Warn about retain cycles where a block captures the LHS, but
14182  // not if the LHS is a simple variable into which the block is
14183  // being stored...unless that variable can be captured by reference!
14184  const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14185  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14186  if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14187  checkRetainCycles(LHSExpr, RHS.get());
14188  }
14189 
14190  if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14192  // It is safe to assign a weak reference into a strong variable.
14193  // Although this code can still have problems:
14194  // id x = self.weakProp;
14195  // id y = self.weakProp;
14196  // we do not warn to warn spuriously when 'x' and 'y' are on separate
14197  // paths through the function. This should be revisited if
14198  // -Wrepeated-use-of-weak is made flow-sensitive.
14199  // For ObjCWeak only, we do not warn if the assign is to a non-weak
14200  // variable, which will be valid for the current autorelease scope.
14201  if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14202  RHS.get()->getBeginLoc()))
14204 
14205  } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14206  checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14207  }
14208  }
14209  } else {
14210  // Compound assignment "x += y"
14211  ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14212  }
14213 
14214  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
14215  RHS.get(), AA_Assigning))
14216  return QualType();
14217 
14218  CheckForNullPointerDereference(*this, LHSExpr);
14219 
14220  if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14221  if (CompoundType.isNull()) {
14222  // C++2a [expr.ass]p5:
14223  // A simple-assignment whose left operand is of a volatile-qualified
14224  // type is deprecated unless the assignment is either a discarded-value
14225  // expression or an unevaluated operand
14226  ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14227  }
14228  }
14229 
14230  // C11 6.5.16p3: The type of an assignment expression is the type of the
14231  // left operand would have after lvalue conversion.
14232  // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14233  // qualified type, the value has the unqualified version of the type of the
14234  // lvalue; additionally, if the lvalue has atomic type, the value has the
14235  // non-atomic version of the type of the lvalue.
14236  // C++ 5.17p1: the type of the assignment expression is that of its left
14237  // operand.
14238  return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14239 }
14240 
14241 // Scenarios to ignore if expression E is:
14242 // 1. an explicit cast expression into void
14243 // 2. a function call expression that returns void
14244 static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14245  E = E->IgnoreParens();
14246 
14247  if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14248  if (CE->getCastKind() == CK_ToVoid) {
14249  return true;
14250  }
14251 
14252  // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14253  if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14254  CE->getSubExpr()->getType()->isDependentType()) {
14255  return true;
14256  }
14257  }
14258 
14259  if (const auto *CE = dyn_cast<CallExpr>(E))
14260  return CE->getCallReturnType(Context)->isVoidType();
14261  return false;
14262 }
14263 
14264 // Look for instances where it is likely the comma operator is confused with
14265 // another operator. There is an explicit list of acceptable expressions for
14266 // the left hand side of the comma operator, otherwise emit a warning.
14268  // No warnings in macros
14269  if (Loc.isMacroID())
14270  return;
14271 
14272  // Don't warn in template instantiations.
14274  return;
14275 
14276  // Scope isn't fine-grained enough to explicitly list the specific cases, so
14277  // instead, skip more than needed, then call back into here with the
14278  // CommaVisitor in SemaStmt.cpp.
14279  // The listed locations are the initialization and increment portions
14280  // of a for loop. The additional checks are on the condition of
14281  // if statements, do/while loops, and for loops.
14282  // Differences in scope flags for C89 mode requires the extra logic.
14283  const unsigned ForIncrementFlags =
14284  getLangOpts().C99 || getLangOpts().CPlusPlus
14287  const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14288  const unsigned ScopeFlags = getCurScope()->getFlags();
14289  if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14290  (ScopeFlags & ForInitFlags) == ForInitFlags)
14291  return;
14292 
14293  // If there are multiple comma operators used together, get the RHS of the
14294  // of the comma operator as the LHS.
14295  while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14296  if (BO->getOpcode() != BO_Comma)
14297  break;
14298  LHS = BO->getRHS();
14299  }
14300 
14301  // Only allow some expressions on LHS to not warn.
14302  if (IgnoreCommaOperand(LHS, Context))
14303  return;
14304 
14305  Diag(Loc, diag::warn_comma_operator);
14306  Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14307  << LHS->getSourceRange()
14309  LangOpts.CPlusPlus ? "static_cast<void>("
14310  : "(void)(")
14312  ")");
14313 }
14314 
14315 // C99 6.5.17
14317  SourceLocation Loc) {
14318  LHS = S.CheckPlaceholderExpr(LHS.get());
14319  RHS = S.CheckPlaceholderExpr(RHS.get());
14320  if (LHS.isInvalid() || RHS.isInvalid())
14321  return QualType();
14322 
14323  // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14324  // operands, but not unary promotions.
14325  // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14326 
14327  // So we treat the LHS as a ignored value, and in C++ we allow the
14328  // containing site to determine what should be done with the RHS.
14329  LHS = S.IgnoredValueConversions(LHS.get());
14330  if (LHS.isInvalid())
14331  return QualType();
14332 
14333  S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14334 
14335  if (!S.getLangOpts().CPlusPlus) {
14337  if (RHS.isInvalid())
14338  return QualType();
14339  if (!RHS.get()->getType()->isVoidType())
14340  S.RequireCompleteType(Loc, RHS.get()->getType(),
14341  diag::err_incomplete_type);
14342  }
14343 
14344  if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14345  S.DiagnoseCommaOperator(LHS.get(), Loc);
14346 
14347  return RHS.get()->getType();
14348 }
14349 
14350 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14351 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14353  ExprValueKind &VK,
14354  ExprObjectKind &OK,
14355  SourceLocation OpLoc,
14356  bool IsInc, bool IsPrefix) {
14357  if (Op->isTypeDependent())
14358  return S.Context.DependentTy;
14359 
14360  QualType ResType = Op->getType();
14361  // Atomic types can be used for increment / decrement where the non-atomic
14362  // versions can, so ignore the _Atomic() specifier for the purpose of
14363  // checking.
14364  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14365  ResType = ResAtomicType->getValueType();
14366 
14367  assert(!ResType.isNull() && "no type for increment/decrement expression");
14368 
14369  if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14370  // Decrement of bool is not allowed.
14371  if (!IsInc) {
14372  S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14373  return QualType();
14374  }
14375  // Increment of bool sets it to true, but is deprecated.
14376  S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14377  : diag::warn_increment_bool)
14378  << Op->getSourceRange();
14379  } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14380  // Error on enum increments and decrements in C++ mode
14381  S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14382  return QualType();
14383  } else if (ResType->isRealType()) {
14384  // OK!
14385  } else if (ResType->isPointerType()) {
14386  // C99 6.5.2.4p2, 6.5.6p2
14387  if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14388  return QualType();
14389  } else if (ResType->isObjCObjectPointerType()) {
14390  // On modern runtimes, ObjC pointer arithmetic is forbidden.
14391  // Otherwise, we just need a complete type.
14392  if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14393  checkArithmeticOnObjCPointer(S, OpLoc, Op))
14394  return QualType();
14395  } else if (ResType->isAnyComplexType()) {
14396  // C99 does not support ++/-- on complex types, we allow as an extension.
14397  S.Diag(OpLoc, diag::ext_integer_increment_complex)
14398  << ResType << Op->getSourceRange();
14399  } else if (ResType->isPlaceholderType()) {
14400  ExprResult PR = S.CheckPlaceholderExpr(Op);
14401  if (PR.isInvalid()) return QualType();
14402  return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14403  IsInc, IsPrefix);
14404  } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14405  // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14406  } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14407  (ResType->castAs<VectorType>()->getVectorKind() !=
14409  // The z vector extensions allow ++ and -- for non-bool vectors.
14410  } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
14411  ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14412  // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14413  } else {
14414  S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14415  << ResType << int(IsInc) << Op->getSourceRange();
14416  return QualType();
14417  }
14418  // At this point, we know we have a real, complex or pointer type.
14419  // Now make sure the operand is a modifiable lvalue.
14420  if (CheckForModifiableLvalue(Op, OpLoc, S))
14421  return QualType();
14422  if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14423  // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14424  // An operand with volatile-qualified type is deprecated
14425  S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14426  << IsInc << ResType;
14427  }
14428  // In C++, a prefix increment is the same type as the operand. Otherwise
14429  // (in C or with postfix), the increment is the unqualified type of the
14430  // operand.
14431  if (IsPrefix && S.getLangOpts().CPlusPlus) {
14432  VK = VK_LValue;
14433  OK = Op->getObjectKind();
14434  return ResType;
14435  } else {
14436  VK = VK_PRValue;
14437  return ResType.getUnqualifiedType();
14438  }
14439 }
14440 
14441 
14442 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14443 /// This routine allows us to typecheck complex/recursive expressions
14444 /// where the declaration is needed for type checking. We only need to
14445 /// handle cases when the expression references a function designator
14446 /// or is an lvalue. Here are some examples:
14447 /// - &(x) => x
14448 /// - &*****f => f for f a function designator.
14449 /// - &s.xx => s
14450 /// - &s.zz[1].yy -> s, if zz is an array
14451 /// - *(x + 1) -> x, if x is an array
14452 /// - &"123"[2] -> 0
14453 /// - & __real__ x -> x
14454 ///
14455 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14456 /// members.
14458  switch (E->getStmtClass()) {
14459  case Stmt::DeclRefExprClass:
14460  return cast<DeclRefExpr>(E)->getDecl();
14461  case Stmt::MemberExprClass:
14462  // If this is an arrow operator, the address is an offset from
14463  // the base's value, so the object the base refers to is
14464  // irrelevant.
14465  if (cast<MemberExpr>(E)->isArrow())
14466  return nullptr;
14467  // Otherwise, the expression refers to a part of the base
14468  return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14469  case Stmt::ArraySubscriptExprClass: {
14470  // FIXME: This code shouldn't be necessary! We should catch the implicit
14471  // promotion of register arrays earlier.
14472  Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14473  if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14474  if (ICE->getSubExpr()->getType()->isArrayType())
14475  return getPrimaryDecl(ICE->getSubExpr());
14476  }
14477  return nullptr;
14478  }
14479  case Stmt::UnaryOperatorClass: {
14480  UnaryOperator *UO = cast<UnaryOperator>(E);
14481 
14482  switch(UO->getOpcode()) {
14483  case UO_Real:
14484  case UO_Imag:
14485  case UO_Extension:
14486  return getPrimaryDecl(UO->getSubExpr());
14487  default:
14488  return nullptr;
14489  }
14490  }
14491  case Stmt::ParenExprClass:
14492  return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14493  case Stmt::ImplicitCastExprClass:
14494  // If the result of an implicit cast is an l-value, we care about
14495  // the sub-expression; otherwise, the result here doesn't matter.
14496  return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14497  case Stmt::CXXUuidofExprClass:
14498  return cast<CXXUuidofExpr>(E)->getGuidDecl();
14499  default:
14500  return nullptr;
14501  }
14502 }
14503 
14504 namespace {
14505 enum {
14506  AO_Bit_Field = 0,
14507  AO_Vector_Element = 1,
14508  AO_Property_Expansion = 2,
14509  AO_Register_Variable = 3,
14510  AO_Matrix_Element = 4,
14511  AO_No_Error = 5
14512 };
14513 }
14514 /// Diagnose invalid operand for address of operations.
14515 ///
14516 /// \param Type The type of operand which cannot have its address taken.
14518  Expr *E, unsigned Type) {
14519  S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14520 }
14521 
14522 /// CheckAddressOfOperand - The operand of & must be either a function
14523 /// designator or an lvalue designating an object. If it is an lvalue, the
14524 /// object cannot be declared with storage class register or be a bit field.
14525 /// Note: The usual conversions are *not* applied to the operand of the &
14526 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14527 /// In C++, the operand might be an overloaded function name, in which case
14528 /// we allow the '&' but retain the overloaded-function type.
14530  if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14531  if (PTy->getKind() == BuiltinType::Overload) {
14532  Expr *E = OrigOp.get()->IgnoreParens();
14533  if (!isa<OverloadExpr>(E)) {
14534  assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14535  Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14536  << OrigOp.get()->getSourceRange();
14537  return QualType();
14538  }
14539 
14540  OverloadExpr *Ovl = cast<OverloadExpr>(E);
14541  if (isa<UnresolvedMemberExpr>(Ovl))
14543  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14544  << OrigOp.get()->getSourceRange();
14545  return QualType();
14546  }
14547 
14548  return Context.OverloadTy;
14549  }
14550 
14551  if (PTy->getKind() == BuiltinType::UnknownAny)
14552  return Context.UnknownAnyTy;
14553 
14554  if (PTy->getKind() == BuiltinType::BoundMember) {
14555  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14556  << OrigOp.get()->getSourceRange();
14557  return QualType();
14558  }
14559 
14560  OrigOp = CheckPlaceholderExpr(OrigOp.get());
14561  if (OrigOp.isInvalid()) return QualType();
14562  }
14563 
14564  if (OrigOp.get()->isTypeDependent())
14565  return Context.DependentTy;
14566 
14567  assert(!OrigOp.get()->hasPlaceholderType());
14568 
14569  // Make sure to ignore parentheses in subsequent checks
14570  Expr *op = OrigOp.get()->IgnoreParens();
14571 
14572  // In OpenCL captures for blocks called as lambda functions
14573  // are located in the private address space. Blocks used in
14574  // enqueue_kernel can be located in a different address space
14575  // depending on a vendor implementation. Thus preventing
14576  // taking an address of the capture to avoid invalid AS casts.
14577  if (LangOpts.OpenCL) {
14578  auto* VarRef = dyn_cast<DeclRefExpr>(op);
14579  if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14580  Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14581  return QualType();
14582  }
14583  }
14584 
14585  if (getLangOpts().C99) {
14586  // Implement C99-only parts of addressof rules.
14587  if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14588  if (uOp->getOpcode() == UO_Deref)
14589  // Per C99 6.5.3.2, the address of a deref always returns a valid result
14590  // (assuming the deref expression is valid).
14591  return uOp->getSubExpr()->getType();
14592  }
14593  // Technically, there should be a check for array subscript
14594  // expressions here, but the result of one is always an lvalue anyway.
14595  }
14596  ValueDecl *dcl = getPrimaryDecl(op);
14597 
14598  if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14599  if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14600  op->getBeginLoc()))
14601  return QualType();
14602 
14604  unsigned AddressOfError = AO_No_Error;
14605 
14606  if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14607  bool sfinae = (bool)isSFINAEContext();
14608  Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14609  : diag::ext_typecheck_addrof_temporary)
14610  << op->getType() << op->getSourceRange();
14611  if (sfinae)
14612  return QualType();
14613  // Materialize the temporary as an lvalue so that we can take its address.
14614  OrigOp = op =
14615  CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14616  } else if (isa<ObjCSelectorExpr>(op)) {
14617  return Context.getPointerType(op->getType());
14618  } else if (lval == Expr::LV_MemberFunction) {
14619  // If it's an instance method, make a member pointer.
14620  // The expression must have exactly the form &A::foo.
14621 
14622  // If the underlying expression isn't a decl ref, give up.
14623  if (!isa<DeclRefExpr>(op)) {
14624  Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14625  << OrigOp.get()->getSourceRange();
14626  return QualType();
14627  }
14628  DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14629  CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14630 
14631  // The id-expression was parenthesized.
14632  if (OrigOp.get() != DRE) {
14633  Diag(OpLoc, diag::err_parens_pointer_member_function)
14634  << OrigOp.get()->getSourceRange();
14635 
14636  // The method was named without a qualifier.
14637  } else if (!DRE->getQualifier()) {
14638  if (MD->getParent()->getName().empty())
14639  Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14640  << op->getSourceRange();
14641  else {
14642  SmallString<32> Str;
14643  StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14644  Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14645  << op->getSourceRange()
14647  }
14648  }
14649 
14650  // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14651  if (isa<CXXDestructorDecl>(MD))
14652  Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14653 
14656  // Under the MS ABI, lock down the inheritance model now.
14658  (void)isCompleteType(OpLoc, MPTy);
14659  return MPTy;
14660  } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14661  // C99 6.5.3.2p1
14662  // The operand must be either an l-value or a function designator
14663  if (!op->getType()->isFunctionType()) {
14664  // Use a special diagnostic for loads from property references.
14665  if (isa<PseudoObjectExpr>(op)) {
14666  AddressOfError = AO_Property_Expansion;
14667  } else {
14668  Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14669  << op->getType() << op->getSourceRange();
14670  return QualType();
14671  }
14672  }
14673  } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14674  // The operand cannot be a bit-field
14675  AddressOfError = AO_Bit_Field;
14676  } else if (op->getObjectKind() == OK_VectorComponent) {
14677  // The operand cannot be an element of a vector
14678  AddressOfError = AO_Vector_Element;
14679  } else if (op->getObjectKind() == OK_MatrixComponent) {
14680  // The operand cannot be an element of a matrix.
14681  AddressOfError = AO_Matrix_Element;
14682  } else if (dcl) { // C99 6.5.3.2p1
14683  // We have an lvalue with a decl. Make sure the decl is not declared
14684  // with the register storage-class specifier.
14685  if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14686  // in C++ it is not error to take address of a register
14687  // variable (c++03 7.1.1P3)
14688  if (vd->getStorageClass() == SC_Register &&
14689  !getLangOpts().CPlusPlus) {
14690  AddressOfError = AO_Register_Variable;
14691  }
14692  } else if (isa<MSPropertyDecl>(dcl)) {
14693  AddressOfError = AO_Property_Expansion;
14694  } else if (isa<FunctionTemplateDecl>(dcl)) {
14695  return Context.OverloadTy;
14696  } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14697  // Okay: we can take the address of a field.
14698  // Could be a pointer to member, though, if there is an explicit
14699  // scope qualifier for the class.
14700  if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14701  DeclContext *Ctx = dcl->getDeclContext();
14702  if (Ctx && Ctx->isRecord()) {
14703  if (dcl->getType()->isReferenceType()) {
14704  Diag(OpLoc,
14705  diag::err_cannot_form_pointer_to_member_of_reference_type)
14706  << dcl->getDeclName() << dcl->getType();
14707  return QualType();
14708  }
14709 
14710  while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14711  Ctx = Ctx->getParent();
14712 
14714  op->getType(),
14715  Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14716  // Under the MS ABI, lock down the inheritance model now.
14718  (void)isCompleteType(OpLoc, MPTy);
14719  return MPTy;
14720  }
14721  }
14724  llvm_unreachable("Unknown/unexpected decl type");
14725  }
14726 
14727  if (AddressOfError != AO_No_Error) {
14728  diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14729  return QualType();
14730  }
14731 
14732  if (lval == Expr::LV_IncompleteVoidType) {
14733  // Taking the address of a void variable is technically illegal, but we
14734  // allow it in cases which are otherwise valid.
14735  // Example: "extern void x; void* y = &x;".
14736  Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14737  }
14738 
14739  // If the operand has type "type", the result has type "pointer to type".
14740  if (op->getType()->isObjCObjectType())
14742 
14743  CheckAddressOfPackedMember(op);
14744 
14745  return Context.getPointerType(op->getType());
14746 }
14747 
14748 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14749  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14750  if (!DRE)
14751  return;
14752  const Decl *D = DRE->getDecl();
14753  if (!D)
14754  return;
14755  const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14756  if (!Param)
14757  return;
14758  if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14759  if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14760  return;
14761  if (FunctionScopeInfo *FD = S.getCurFunction())
14762  FD->ModifiedNonNullParams.insert(Param);
14763 }
14764 
14765 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14767  SourceLocation OpLoc,
14768  bool IsAfterAmp = false) {
14769  if (Op->isTypeDependent())
14770  return S.Context.DependentTy;
14771 
14772  ExprResult ConvResult = S.UsualUnaryConversions(Op);
14773  if (ConvResult.isInvalid())
14774  return QualType();
14775  Op = ConvResult.get();
14776  QualType OpTy = Op->getType();
14777  QualType Result;
14778 
14779  if (isa<CXXReinterpretCastExpr>(Op)) {
14780  QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14781  S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14782  Op->getSourceRange());
14783  }
14784 
14785  if (const PointerType *PT = OpTy->getAs<PointerType>())
14786  {
14787  Result = PT->getPointeeType();
14788  }
14789  else if (const ObjCObjectPointerType *OPT =
14790  OpTy->getAs<ObjCObjectPointerType>())
14791  Result = OPT->getPointeeType();
14792  else {
14793  ExprResult PR = S.CheckPlaceholderExpr(Op);
14794  if (PR.isInvalid()) return QualType();
14795  if (PR.get() != Op)
14796  return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14797  }
14798 
14799  if (Result.isNull()) {
14800  S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14801  << OpTy << Op->getSourceRange();
14802  return QualType();
14803  }
14804 
14805  if (Result->isVoidType()) {
14806  // C++ [expr.unary.op]p1:
14807  // [...] the expression to which [the unary * operator] is applied shall
14808  // be a pointer to an object type, or a pointer to a function type
14809  LangOptions LO = S.getLangOpts();
14810  if (LO.CPlusPlus)
14811  S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer_cpp)
14812  << OpTy << Op->getSourceRange();
14813  else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14814  S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14815  << OpTy << Op->getSourceRange();
14816  }
14817 
14818  // Dereferences are usually l-values...
14819  VK = VK_LValue;
14820 
14821  // ...except that certain expressions are never l-values in C.
14822  if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14823  VK = VK_PRValue;
14824 
14825  return Result;
14826 }
14827 
14828 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14829  BinaryOperatorKind Opc;
14830  switch (Kind) {
14831  default: llvm_unreachable("Unknown binop!");
14832  case tok::periodstar: Opc = BO_PtrMemD; break;
14833  case tok::arrowstar: Opc = BO_PtrMemI; break;
14834  case tok::star: Opc = BO_Mul; break;
14835  case tok::slash: Opc = BO_Div; break;
14836  case tok::percent: Opc = BO_Rem; break;
14837  case tok::plus: Opc = BO_Add; break;
14838  case tok::minus: Opc = BO_Sub; break;
14839  case tok::lessless: Opc = BO_Shl; break;
14840  case tok::greatergreater: Opc = BO_Shr; break;
14841  case tok::lessequal: Opc = BO_LE; break;
14842  case tok::less: Opc = BO_LT; break;
14843  case tok::greaterequal: Opc = BO_GE; break;
14844  case tok::greater: Opc = BO_GT; break;
14845  case tok::exclaimequal: Opc = BO_NE; break;
14846  case tok::equalequal: Opc = BO_EQ; break;
14847  case tok::spaceship: Opc = BO_Cmp; break;
14848  case tok::amp: Opc = BO_And; break;
14849  case tok::caret: Opc = BO_Xor; break;
14850  case tok::pipe: Opc = BO_Or; break;
14851  case tok::ampamp: Opc = BO_LAnd; break;
14852  case tok::pipepipe: Opc = BO_LOr; break;
14853  case tok::equal: Opc = BO_Assign; break;
14854  case tok::starequal: Opc = BO_MulAssign; break;
14855  case tok::slashequal: Opc = BO_DivAssign; break;
14856  case tok::percentequal: Opc = BO_RemAssign; break;
14857  case tok::plusequal: Opc = BO_AddAssign; break;
14858  case tok::minusequal: Opc = BO_SubAssign; break;
14859  case tok::lesslessequal: Opc = BO_ShlAssign; break;
14860  case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14861  case tok::ampequal: Opc = BO_AndAssign; break;
14862  case tok::caretequal: Opc = BO_XorAssign; break;
14863  case tok::pipeequal: Opc = BO_OrAssign; break;
14864  case tok::comma: Opc = BO_Comma; break;
14865  }
14866  return Opc;
14867 }
14868 
14870  tok::TokenKind Kind) {
14871  UnaryOperatorKind Opc;
14872  switch (Kind) {
14873  default: llvm_unreachable("Unknown unary op!");
14874  case tok::plusplus: Opc = UO_PreInc; break;
14875  case tok::minusminus: Opc = UO_PreDec; break;
14876  case tok::amp: Opc = UO_AddrOf; break;
14877  case tok::star: Opc = UO_Deref; break;
14878  case tok::plus: Opc = UO_Plus; break;
14879  case tok::minus: Opc = UO_Minus; break;
14880  case tok::tilde: Opc = UO_Not; break;
14881  case tok::exclaim: Opc = UO_LNot; break;
14882  case tok::kw___real: Opc = UO_Real; break;
14883  case tok::kw___imag: Opc = UO_Imag; break;
14884  case tok::kw___extension__: Opc = UO_Extension; break;
14885  }
14886  return Opc;
14887 }
14888 
14889 const FieldDecl *
14891  // Explore the case for adding 'this->' to the LHS of a self assignment, very
14892  // common for setters.
14893  // struct A {
14894  // int X;
14895  // -void setX(int X) { X = X; }
14896  // +void setX(int X) { this->X = X; }
14897  // };
14898 
14899  // Only consider parameters for self assignment fixes.
14900  if (!isa<ParmVarDecl>(SelfAssigned))
14901  return nullptr;
14902  const auto *Method =
14903  dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14904  if (!Method)
14905  return nullptr;
14906 
14907  const CXXRecordDecl *Parent = Method->getParent();
14908  // In theory this is fixable if the lambda explicitly captures this, but
14909  // that's added complexity that's rarely going to be used.
14910  if (Parent->isLambda())
14911  return nullptr;
14912 
14913  // FIXME: Use an actual Lookup operation instead of just traversing fields
14914  // in order to get base class fields.
14915  auto Field =
14916  llvm::find_if(Parent->fields(),
14917  [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14918  return F->getDeclName() == Name;
14919  });
14920  return (Field != Parent->field_end()) ? *Field : nullptr;
14921 }
14922 
14923 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14924 /// This warning suppressed in the event of macro expansions.
14925 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14926  SourceLocation OpLoc, bool IsBuiltin) {
14927  if (S.inTemplateInstantiation())
14928  return;
14929  if (S.isUnevaluatedContext())
14930  return;
14931  if (OpLoc.isInvalid() || OpLoc.isMacroID())
14932  return;
14933  LHSExpr = LHSExpr->IgnoreParenImpCasts();
14934  RHSExpr = RHSExpr->IgnoreParenImpCasts();
14935  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14936  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14937  if (!LHSDeclRef || !RHSDeclRef ||
14938  LHSDeclRef->getLocation().isMacroID() ||
14939  RHSDeclRef->getLocation().isMacroID())
14940  return;
14941  const ValueDecl *LHSDecl =
14942  cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14943  const ValueDecl *RHSDecl =
14944  cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14945  if (LHSDecl != RHSDecl)
14946  return;
14947  if (LHSDecl->getType().isVolatileQualified())
14948  return;
14949  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14950  if (RefTy->getPointeeType().isVolatileQualified())
14951  return;
14952 
14953  auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14954  : diag::warn_self_assignment_overloaded)
14955  << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14956  << RHSExpr->getSourceRange();
14957  if (const FieldDecl *SelfAssignField =
14959  Diag << 1 << SelfAssignField
14960  << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14961  else
14962  Diag << 0;
14963 }
14964 
14965 /// Check if a bitwise-& is performed on an Objective-C pointer. This
14966 /// is usually indicative of introspection within the Objective-C pointer.
14968  SourceLocation OpLoc) {
14969  if (!S.getLangOpts().ObjC)
14970  return;
14971 
14972  const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14973  const Expr *LHS = L.get();
14974  const Expr *RHS = R.get();
14975 
14977  ObjCPointerExpr = LHS;
14978  OtherExpr = RHS;
14979  }
14980  else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14981  ObjCPointerExpr = RHS;
14982  OtherExpr = LHS;
14983  }
14984 
14985  // This warning is deliberately made very specific to reduce false
14986  // positives with logic that uses '&' for hashing. This logic mainly
14987  // looks for code trying to introspect into tagged pointers, which
14988  // code should generally never do.
14989  if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14990  unsigned Diag = diag::warn_objc_pointer_masking;
14991  // Determine if we are introspecting the result of performSelectorXXX.
14992  const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14993  // Special case messages to -performSelector and friends, which
14994  // can return non-pointer values boxed in a pointer value.
14995  // Some clients may wish to silence warnings in this subcase.
14996  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14997  Selector S = ME->getSelector();
14998  StringRef SelArg0 = S.getNameForSlot(0);
14999  if (SelArg0.startswith("performSelector"))
15000  Diag = diag::warn_objc_pointer_masking_performSelector;
15001  }
15002 
15003  S.Diag(OpLoc, Diag)
15004  << ObjCPointerExpr->getSourceRange();
15005  }
15006 }
15007 
15009  if (!E)
15010  return nullptr;
15011  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
15012  return DRE->getDecl();
15013  if (auto *ME = dyn_cast<MemberExpr>(E))
15014  return ME->getMemberDecl();
15015  if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
15016  return IRE->getDecl();
15017  return nullptr;
15018 }
15019 
15020 // This helper function promotes a binary operator's operands (which are of a
15021 // half vector type) to a vector of floats and then truncates the result to
15022 // a vector of either half or short.
15024  BinaryOperatorKind Opc, QualType ResultTy,
15026  bool IsCompAssign, SourceLocation OpLoc,
15027  FPOptionsOverride FPFeatures) {
15028  auto &Context = S.getASTContext();
15029  assert((isVector(ResultTy, Context.HalfTy) ||
15030  isVector(ResultTy, Context.ShortTy)) &&
15031  "Result must be a vector of half or short");
15032  assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15033  isVector(RHS.get()->getType(), Context.HalfTy) &&
15034  "both operands expected to be a half vector");
15035 
15036  RHS = convertVector(RHS.get(), Context.FloatTy, S);
15037  QualType BinOpResTy = RHS.get()->getType();
15038 
15039  // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15040  // change BinOpResTy to a vector of ints.
15041  if (isVector(ResultTy, Context.ShortTy))
15042  BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15043 
15044  if (IsCompAssign)
15045  return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15046  ResultTy, VK, OK, OpLoc, FPFeatures,
15047  BinOpResTy, BinOpResTy);
15048 
15049  LHS = convertVector(LHS.get(), Context.FloatTy, S);
15050  auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15051  BinOpResTy, VK, OK, OpLoc, FPFeatures);
15052  return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15053 }
15054 
15055 static std::pair<ExprResult, ExprResult>
15057  Expr *RHSExpr) {
15058  ExprResult LHS = LHSExpr, RHS = RHSExpr;
15059  if (!S.Context.isDependenceAllowed()) {
15060  // C cannot handle TypoExpr nodes on either side of a binop because it
15061  // doesn't handle dependent types properly, so make sure any TypoExprs have
15062  // been dealt with before checking the operands.
15063  LHS = S.CorrectDelayedTyposInExpr(LHS);
15064  RHS = S.CorrectDelayedTyposInExpr(
15065  RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
15066  [Opc, LHS](Expr *E) {
15067  if (Opc != BO_Assign)
15068  return ExprResult(E);
15069  // Avoid correcting the RHS to the same Expr as the LHS.
15070  Decl *D = getDeclFromExpr(E);
15071  return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
15072  });
15073  }
15074  return std::make_pair(LHS, RHS);
15075 }
15076 
15077 /// Returns true if conversion between vectors of halfs and vectors of floats
15078 /// is needed.
15079 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15080  Expr *E0, Expr *E1 = nullptr) {
15081  if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15083  return false;
15084 
15085  auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15086  QualType Ty = E->IgnoreImplicit()->getType();
15087 
15088  // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15089  // to vectors of floats. Although the element type of the vectors is __fp16,
15090  // the vectors shouldn't be treated as storage-only types. See the
15091  // discussion here: https://reviews.llvm.org/rG825235c140e7
15092  if (const VectorType *VT = Ty->getAs<VectorType>()) {
15093  if (VT->getVectorKind() == VectorType::NeonVector)
15094  return false;
15095  return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15096  }
15097  return false;
15098  };
15099 
15100  return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15101 }
15102 
15103 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
15104 /// operator @p Opc at location @c TokLoc. This routine only supports
15105 /// built-in operations; ActOnBinOp handles overloaded operators.
15107  BinaryOperatorKind Opc,
15108  Expr *LHSExpr, Expr *RHSExpr) {
15109  if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15110  // The syntax only allows initializer lists on the RHS of assignment,
15111  // so we don't need to worry about accepting invalid code for
15112  // non-assignment operators.
15113  // C++11 5.17p9:
15114  // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15115  // of x = {} is x = T().
15117  RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15118  InitializedEntity Entity =
15120  InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15121  ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15122  if (Init.isInvalid())
15123  return Init;
15124  RHSExpr = Init.get();
15125  }
15126 
15127  ExprResult LHS = LHSExpr, RHS = RHSExpr;
15128  QualType ResultTy; // Result type of the binary operator.
15129  // The following two variables are used for compound assignment operators
15130  QualType CompLHSTy; // Type of LHS after promotions for computation
15131  QualType CompResultTy; // Type of computation result
15134  bool ConvertHalfVec = false;
15135 
15136  std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15137  if (!LHS.isUsable() || !RHS.isUsable())
15138  return ExprError();
15139 
15140  if (getLangOpts().OpenCL) {
15141  QualType LHSTy = LHSExpr->getType();
15142  QualType RHSTy = RHSExpr->getType();
15143  // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15144  // the ATOMIC_VAR_INIT macro.
15145  if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15146  SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15147  if (BO_Assign == Opc)
15148  Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15149  else
15150  ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15151  return ExprError();
15152  }
15153 
15154  // OpenCL special types - image, sampler, pipe, and blocks are to be used
15155  // only with a builtin functions and therefore should be disallowed here.
15156  if (LHSTy->isImageType() || RHSTy->isImageType() ||
15157  LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15158  LHSTy->isPipeType() || RHSTy->isPipeType() ||
15159  LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15160  ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15161  return ExprError();
15162  }
15163  }
15164 
15165  checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15166  checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15167 
15168  switch (Opc) {
15169  case BO_Assign:
15170  ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15171  if (getLangOpts().CPlusPlus &&
15172  LHS.get()->getObjectKind() != OK_ObjCProperty) {
15173  VK = LHS.get()->getValueKind();
15174  OK = LHS.get()->getObjectKind();
15175  }
15176  if (!ResultTy.isNull()) {
15177  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15178  DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15179 
15180  // Avoid copying a block to the heap if the block is assigned to a local
15181  // auto variable that is declared in the same scope as the block. This
15182  // optimization is unsafe if the local variable is declared in an outer
15183  // scope. For example:
15184  //
15185  // BlockTy b;
15186  // {
15187  // b = ^{...};
15188  // }
15189  // // It is unsafe to invoke the block here if it wasn't copied to the
15190  // // heap.
15191  // b();
15192 
15193  if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15194  if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15195  if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15196  if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15197  BE->getBlockDecl()->setCanAvoidCopyToHeap();
15198 
15200  checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15202  }
15203  RecordModifiableNonNullParam(*this, LHS.get());
15204  break;
15205  case BO_PtrMemD:
15206  case BO_PtrMemI:
15207  ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15208  Opc == BO_PtrMemI);
15209  break;
15210  case BO_Mul:
15211  case BO_Div:
15212  ConvertHalfVec = true;
15213  ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
15214  Opc == BO_Div);
15215  break;
15216  case BO_Rem:
15217  ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15218  break;
15219  case BO_Add:
15220  ConvertHalfVec = true;
15221  ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15222  break;
15223  case BO_Sub:
15224  ConvertHalfVec = true;
15225  ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
15226  break;
15227  case BO_Shl:
15228  case BO_Shr:
15229  ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15230  break;
15231  case BO_LE:
15232  case BO_LT:
15233  case BO_GE:
15234  case BO_GT:
15235  ConvertHalfVec = true;
15236  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15237  break;
15238  case BO_EQ:
15239  case BO_NE:
15240  ConvertHalfVec = true;
15241  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15242  break;
15243  case BO_Cmp:
15244  ConvertHalfVec = true;
15245  ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15246  assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15247  break;
15248  case BO_And:
15249  checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15250  [[fallthrough]];
15251  case BO_Xor:
15252  case BO_Or:
15253  ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15254  break;
15255  case BO_LAnd:
15256  case BO_LOr:
15257  ConvertHalfVec = true;
15258  ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15259  break;
15260  case BO_MulAssign:
15261  case BO_DivAssign:
15262  ConvertHalfVec = true;
15263  CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
15264  Opc == BO_DivAssign);
15265  CompLHSTy = CompResultTy;
15266  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15267  ResultTy =
15268  CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15269  break;
15270  case BO_RemAssign:
15271  CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15272  CompLHSTy = CompResultTy;
15273  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15274  ResultTy =
15275  CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15276  break;
15277  case BO_AddAssign:
15278  ConvertHalfVec = true;
15279  CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15280  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15281  ResultTy =
15282  CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15283  break;
15284  case BO_SubAssign:
15285  ConvertHalfVec = true;
15286  CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
15287  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15288  ResultTy =
15289  CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15290  break;
15291  case BO_ShlAssign:
15292  case BO_ShrAssign:
15293  CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15294  CompLHSTy = CompResultTy;
15295  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15296  ResultTy =
15297  CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15298  break;
15299  case BO_AndAssign:
15300  case BO_OrAssign: // fallthrough
15301  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15302  [[fallthrough]];
15303  case BO_XorAssign:
15304  CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15305  CompLHSTy = CompResultTy;
15306  if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15307  ResultTy =
15308  CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15309  break;
15310  case BO_Comma:
15311  ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15312  if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15313  VK = RHS.get()->getValueKind();
15314  OK = RHS.get()->getObjectKind();
15315  }
15316  break;
15317  }
15318  if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15319  return ExprError();
15320 
15321  // Some of the binary operations require promoting operands of half vector to
15322  // float vectors and truncating the result back to half vector. For now, we do
15323  // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15324  // arm64).
15325  assert(
15326  (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15327  isVector(LHS.get()->getType(), Context.HalfTy)) &&
15328  "both sides are half vectors or neither sides are");
15329  ConvertHalfVec =
15330  needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15331 
15332  // Check for array bounds violations for both sides of the BinaryOperator
15333  CheckArrayAccess(LHS.get());
15334  CheckArrayAccess(RHS.get());
15335 
15336  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15337  NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15338  &Context.Idents.get("object_setClass"),
15340  if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15341  SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15342  Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15344  "object_setClass(")
15345  << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15346  ",")
15347  << FixItHint::CreateInsertion(RHSLocEnd, ")");
15348  }
15349  else
15350  Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15351  }
15352  else if (const ObjCIvarRefExpr *OIRE =
15353  dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15354  DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15355 
15356  // Opc is not a compound assignment if CompResultTy is null.
15357  if (CompResultTy.isNull()) {
15358  if (ConvertHalfVec)
15359  return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15360  OpLoc, CurFPFeatureOverrides());
15361  return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15362  VK, OK, OpLoc, CurFPFeatureOverrides());
15363  }
15364 
15365  // Handle compound assignments.
15366  if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15367  OK_ObjCProperty) {
15368  VK = VK_LValue;
15369  OK = LHS.get()->getObjectKind();
15370  }
15371 
15372  // The LHS is not converted to the result type for fixed-point compound
15373  // assignment as the common type is computed on demand. Reset the CompLHSTy
15374  // to the LHS type we would have gotten after unary conversions.
15375  if (CompResultTy->isFixedPointType())
15376  CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15377 
15378  if (ConvertHalfVec)
15379  return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15380  OpLoc, CurFPFeatureOverrides());
15381 
15383  Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15384  CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15385 }
15386 
15387 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15388 /// operators are mixed in a way that suggests that the programmer forgot that
15389 /// comparison operators have higher precedence. The most typical example of
15390 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15392  SourceLocation OpLoc, Expr *LHSExpr,
15393  Expr *RHSExpr) {
15394  BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15395  BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15396 
15397  // Check that one of the sides is a comparison operator and the other isn't.
15398  bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15399  bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15400  if (isLeftComp == isRightComp)
15401  return;
15402 
15403  // Bitwise operations are sometimes used as eager logical ops.
15404  // Don't diagnose this.
15405  bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15406  bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15407  if (isLeftBitwise || isRightBitwise)
15408  return;
15409 
15410  SourceRange DiagRange = isLeftComp
15411  ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15412  : SourceRange(OpLoc, RHSExpr->getEndLoc());
15413  StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15414  SourceRange ParensRange =
15415  isLeftComp
15416  ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15417  : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15418 
15419  Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15420  << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15421  SuggestParentheses(Self, OpLoc,
15422  Self.PDiag(diag::note_precedence_silence) << OpStr,
15423  (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15424  SuggestParentheses(Self, OpLoc,
15425  Self.PDiag(diag::note_precedence_bitwise_first)
15427  ParensRange);
15428 }
15429 
15430 /// It accepts a '&&' expr that is inside a '||' one.
15431 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15432 /// in parentheses.
15433 static void
15435  BinaryOperator *Bop) {
15436  assert(Bop->getOpcode() == BO_LAnd);
15437  Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15438  << Bop->getSourceRange() << OpLoc;
15439  SuggestParentheses(Self, Bop->getOperatorLoc(),
15440  Self.PDiag(diag::note_precedence_silence)
15441  << Bop->getOpcodeStr(),
15442  Bop->getSourceRange());
15443 }
15444 
15445 /// Look for '&&' in the left hand of a '||' expr.
15447  Expr *LHSExpr, Expr *RHSExpr) {
15448  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15449  if (Bop->getOpcode() == BO_LAnd) {
15450  // If it's "string_literal && a || b" don't warn since the precedence
15451  // doesn't matter.
15452  if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15453  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15454  } else if (Bop->getOpcode() == BO_LOr) {
15455  if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15456  // If it's "a || b && string_literal || c" we didn't warn earlier for
15457  // "a || b && string_literal", but warn now.
15458  if (RBop->getOpcode() == BO_LAnd &&
15459  isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15460  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15461  }
15462  }
15463  }
15464 }
15465 
15466 /// Look for '&&' in the right hand of a '||' expr.
15468  Expr *LHSExpr, Expr *RHSExpr) {
15469  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15470  if (Bop->getOpcode() == BO_LAnd) {
15471  // If it's "a || b && string_literal" don't warn since the precedence
15472  // doesn't matter.
15473  if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15474  return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15475  }
15476  }
15477 }
15478 
15479 /// Look for bitwise op in the left or right hand of a bitwise op with
15480 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
15481 /// the '&' expression in parentheses.
15483  SourceLocation OpLoc, Expr *SubExpr) {
15484  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15485  if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15486  S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15487  << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15488  << Bop->getSourceRange() << OpLoc;
15489  SuggestParentheses(S, Bop->getOperatorLoc(),
15490  S.PDiag(diag::note_precedence_silence)
15491  << Bop->getOpcodeStr(),
15492  Bop->getSourceRange());
15493  }
15494  }
15495 }
15496 
15498  Expr *SubExpr, StringRef Shift) {
15499  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15500  if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15501  StringRef Op = Bop->getOpcodeStr();
15502  S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15503  << Bop->getSourceRange() << OpLoc << Shift << Op;
15504  SuggestParentheses(S, Bop->getOperatorLoc(),
15505  S.PDiag(diag::note_precedence_silence) << Op,
15506  Bop->getSourceRange());
15507  }
15508  }
15509 }
15510 
15512  Expr *LHSExpr, Expr *RHSExpr) {
15513  CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15514  if (!OCE)
15515  return;
15516 
15517  FunctionDecl *FD = OCE->getDirectCallee();
15518  if (!FD || !FD->isOverloadedOperator())
15519  return;
15520 
15522  if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15523  return;
15524 
15525  S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15526  << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15527  << (Kind == OO_LessLess);
15529  S.PDiag(diag::note_precedence_silence)
15530  << (Kind == OO_LessLess ? "<<" : ">>"),
15531  OCE->getSourceRange());
15533  S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15534  SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15535 }
15536 
15537 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15538 /// precedence.
15540  SourceLocation OpLoc, Expr *LHSExpr,
15541  Expr *RHSExpr){
15542  // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15543  if (BinaryOperator::isBitwiseOp(Opc))
15544  DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15545 
15546  // Diagnose "arg1 & arg2 | arg3"
15547  if ((Opc == BO_Or || Opc == BO_Xor) &&
15548  !OpLoc.isMacroID()/* Don't warn in macros. */) {
15549  DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15550  DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15551  }
15552 
15553  // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15554  // We don't warn for 'assert(a || b && "bad")' since this is safe.
15555  if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15556  DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15557  DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15558  }
15559 
15560  if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15561  || Opc == BO_Shr) {
15562  StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15563  DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15564  DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15565  }
15566 
15567  // Warn on overloaded shift operators and comparisons, such as:
15568  // cout << 5 == 4;
15570  DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15571 }
15572 
15573 // Binary Operators. 'Tok' is the token for the operator.
15576  Expr *LHSExpr, Expr *RHSExpr) {
15577  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15578  assert(LHSExpr && "ActOnBinOp(): missing left expression");
15579  assert(RHSExpr && "ActOnBinOp(): missing right expression");
15580 
15581  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15582  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15583 
15584  return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15585 }
15586 
15588  UnresolvedSetImpl &Functions) {
15590  if (OverOp != OO_None && OverOp != OO_Equal)
15591  LookupOverloadedOperatorName(OverOp, S, Functions);
15592 
15593  // In C++20 onwards, we may have a second operator to look up.
15594  if (getLangOpts().CPlusPlus20) {
15596  LookupOverloadedOperatorName(ExtraOp, S, Functions);
15597  }
15598 }
15599 
15600 /// Build an overloaded binary operator expression in the given scope.
15602  BinaryOperatorKind Opc,
15603  Expr *LHS, Expr *RHS) {
15604  switch (Opc) {
15605  case BO_Assign:
15606  case BO_DivAssign:
15607  case BO_RemAssign:
15608  case BO_SubAssign:
15609  case BO_AndAssign:
15610  case BO_OrAssign:
15611  case BO_XorAssign:
15612  DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15613  CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15614  break;
15615  default:
15616  break;
15617  }
15618 
15619  // Find all of the overloaded operators visible from this point.
15620  UnresolvedSet<16> Functions;
15621  S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15622 
15623  // Build the (potentially-overloaded, potentially-dependent)
15624  // binary operation.
15625  return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15626 }
15627 
15629  BinaryOperatorKind Opc,
15630  Expr *LHSExpr, Expr *RHSExpr) {
15631  ExprResult LHS, RHS;
15632  std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15633  if (!LHS.isUsable() || !RHS.isUsable())
15634  return ExprError();
15635  LHSExpr = LHS.get();
15636  RHSExpr = RHS.get();
15637 
15638  // We want to end up calling one of checkPseudoObjectAssignment
15639  // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15640  // both expressions are overloadable or either is type-dependent),
15641  // or CreateBuiltinBinOp (in any other case). We also want to get
15642  // any placeholder types out of the way.
15643 
15644  // Handle pseudo-objects in the LHS.
15645  if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15646  // Assignments with a pseudo-object l-value need special analysis.
15647  if (pty->getKind() == BuiltinType::PseudoObject &&
15649  return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15650 
15651  // Don't resolve overloads if the other type is overloadable.
15652  if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15653  // We can't actually test that if we still have a placeholder,
15654  // though. Fortunately, none of the exceptions we see in that
15655  // code below are valid when the LHS is an overload set. Note
15656  // that an overload set can be dependently-typed, but it never
15657  // instantiates to having an overloadable type.
15658  ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15659  if (resolvedRHS.isInvalid()) return ExprError();
15660  RHSExpr = resolvedRHS.get();
15661 
15662  if (RHSExpr->isTypeDependent() ||
15663  RHSExpr->getType()->isOverloadableType())
15664  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15665  }
15666 
15667  // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15668  // template, diagnose the missing 'template' keyword instead of diagnosing
15669  // an invalid use of a bound member function.
15670  //
15671  // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15672  // to C++1z [over.over]/1.4, but we already checked for that case above.
15673  if (Opc == BO_LT && inTemplateInstantiation() &&
15674  (pty->getKind() == BuiltinType::BoundMember ||
15675  pty->getKind() == BuiltinType::Overload)) {
15676  auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15677  if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15678  llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15679  return isa<FunctionTemplateDecl>(ND);
15680  })) {
15681  Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15682  : OE->getNameLoc(),
15683  diag::err_template_kw_missing)
15684  << OE->getName().getAsString() << "";
15685  return ExprError();
15686  }
15687  }
15688 
15689  ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15690  if (LHS.isInvalid()) return ExprError();
15691  LHSExpr = LHS.get();
15692  }
15693 
15694  // Handle pseudo-objects in the RHS.
15695  if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15696  // An overload in the RHS can potentially be resolved by the type
15697  // being assigned to.
15698  if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15699  if (getLangOpts().CPlusPlus &&
15700  (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15701  LHSExpr->getType()->isOverloadableType()))
15702  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15703 
15704  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15705  }
15706 
15707  // Don't resolve overloads if the other type is overloadable.
15708  if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15709  LHSExpr->getType()->isOverloadableType())
15710  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15711 
15712  ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15713  if (!resolvedRHS.isUsable()) return ExprError();
15714  RHSExpr = resolvedRHS.get();
15715  }
15716 
15717  if (getLangOpts().CPlusPlus) {
15718  // If either expression is type-dependent, always build an
15719  // overloaded op.
15720  if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15721  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15722 
15723  // Otherwise, build an overloaded op if either expression has an
15724  // overloadable type.
15725  if (LHSExpr->getType()->isOverloadableType() ||
15726  RHSExpr->getType()->isOverloadableType())
15727  return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15728  }
15729 
15730  if (getLangOpts().RecoveryAST &&
15731  (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15732  assert(!getLangOpts().CPlusPlus);
15733  assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15734  "Should only occur in error-recovery path.");
15736  // C [6.15.16] p3:
15737  // An assignment expression has the value of the left operand after the
15738  // assignment, but is not an lvalue.
15740  Context, LHSExpr, RHSExpr, Opc,
15742  OpLoc, CurFPFeatureOverrides());
15743  QualType ResultType;
15744  switch (Opc) {
15745  case BO_Assign:
15746  ResultType = LHSExpr->getType().getUnqualifiedType();
15747  break;
15748  case BO_LT:
15749  case BO_GT:
15750  case BO_LE:
15751  case BO_GE:
15752  case BO_EQ:
15753  case BO_NE:
15754  case BO_LAnd:
15755  case BO_LOr:
15756  // These operators have a fixed result type regardless of operands.
15757  ResultType = Context.IntTy;
15758  break;
15759  case BO_Comma:
15760  ResultType = RHSExpr->getType();
15761  break;
15762  default:
15763  ResultType = Context.DependentTy;
15764  break;
15765  }
15766  return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15767  VK_PRValue, OK_Ordinary, OpLoc,
15769  }
15770 
15771  // Build a built-in binary operation.
15772  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15773 }
15774 
15776  if (T.isNull() || T->isDependentType())
15777  return false;
15778 
15779  if (!Ctx.isPromotableIntegerType(T))
15780  return true;
15781 
15782  return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15783 }
15784 
15786  UnaryOperatorKind Opc, Expr *InputExpr,
15787  bool IsAfterAmp) {
15788  ExprResult Input = InputExpr;
15791  QualType resultType;
15792  bool CanOverflow = false;
15793 
15794  bool ConvertHalfVec = false;
15795  if (getLangOpts().OpenCL) {
15796  QualType Ty = InputExpr->getType();
15797  // The only legal unary operation for atomics is '&'.
15798  if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15799  // OpenCL special types - image, sampler, pipe, and blocks are to be used
15800  // only with a builtin functions and therefore should be disallowed here.
15801  (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15802  || Ty->isBlockPointerType())) {
15803  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15804  << InputExpr->getType()
15805  << Input.get()->getSourceRange());
15806  }
15807  }
15808 
15809  if (getLangOpts().HLSL && OpLoc.isValid()) {
15810  if (Opc == UO_AddrOf)
15811  return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15812  if (Opc == UO_Deref)
15813  return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15814  }
15815 
15816  switch (Opc) {
15817  case UO_PreInc:
15818  case UO_PreDec:
15819  case UO_PostInc:
15820  case UO_PostDec:
15821  resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15822  OpLoc,
15823  Opc == UO_PreInc ||
15824  Opc == UO_PostInc,
15825  Opc == UO_PreInc ||
15826  Opc == UO_PreDec);
15827  CanOverflow = isOverflowingIntegerType(Context, resultType);
15828  break;
15829  case UO_AddrOf:
15830  resultType = CheckAddressOfOperand(Input, OpLoc);
15831  CheckAddressOfNoDeref(InputExpr);
15832  RecordModifiableNonNullParam(*this, InputExpr);
15833  break;
15834  case UO_Deref: {
15835  Input = DefaultFunctionArrayLvalueConversion(Input.get());
15836  if (Input.isInvalid()) return ExprError();
15837  resultType =
15838  CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15839  break;
15840  }
15841  case UO_Plus:
15842  case UO_Minus:
15843  CanOverflow = Opc == UO_Minus &&
15845  Input = UsualUnaryConversions(Input.get());
15846  if (Input.isInvalid()) return ExprError();
15847  // Unary plus and minus require promoting an operand of half vector to a
15848  // float vector and truncating the result back to a half vector. For now, we
15849  // do this only when HalfArgsAndReturns is set (that is, when the target is
15850  // arm or arm64).
15851  ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15852 
15853  // If the operand is a half vector, promote it to a float vector.
15854  if (ConvertHalfVec)
15855  Input = convertVector(Input.get(), Context.FloatTy, *this);
15856  resultType = Input.get()->getType();
15857  if (resultType->isDependentType())
15858  break;
15859  if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15860  break;
15861  else if (resultType->isVectorType() &&
15862  // The z vector extensions don't allow + or - with bool vectors.
15863  (!Context.getLangOpts().ZVector ||
15864  resultType->castAs<VectorType>()->getVectorKind() !=
15866  break;
15867  else if (resultType->isVLSTBuiltinType()) // SVE vectors allow + and -
15868  break;
15869  else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15870  Opc == UO_Plus &&
15871  resultType->isPointerType())
15872  break;
15873 
15874  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15875  << resultType << Input.get()->getSourceRange());
15876 
15877  case UO_Not: // bitwise complement
15878  Input = UsualUnaryConversions(Input.get());
15879  if (Input.isInvalid())
15880  return ExprError();
15881  resultType = Input.get()->getType();
15882  if (resultType->isDependentType())
15883  break;
15884  // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15885  if (resultType->isComplexType() || resultType->isComplexIntegerType())
15886  // C99 does not support '~' for complex conjugation.
15887  Diag(OpLoc, diag::ext_integer_complement_complex)
15888  << resultType << Input.get()->getSourceRange();
15889  else if (resultType->hasIntegerRepresentation())
15890  break;
15891  else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15892  // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15893  // on vector float types.
15894  QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15895  if (!T->isIntegerType())
15896  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15897  << resultType << Input.get()->getSourceRange());
15898  } else {
15899  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15900  << resultType << Input.get()->getSourceRange());
15901  }
15902  break;
15903 
15904  case UO_LNot: // logical negation
15905  // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15906  Input = DefaultFunctionArrayLvalueConversion(Input.get());
15907  if (Input.isInvalid()) return ExprError();
15908  resultType = Input.get()->getType();
15909 
15910  // Though we still have to promote half FP to float...
15911  if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15912  Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15913  resultType = Context.FloatTy;
15914  }
15915 
15916  if (resultType->isDependentType())
15917  break;
15918  if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15919  // C99 6.5.3.3p1: ok, fallthrough;
15920  if (Context.getLangOpts().CPlusPlus) {
15921  // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15922  // operand contextually converted to bool.
15923  Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15924  ScalarTypeToBooleanCastKind(resultType));
15925  } else if (Context.getLangOpts().OpenCL &&
15926  Context.getLangOpts().OpenCLVersion < 120) {
15927  // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15928  // operate on scalar float types.
15929  if (!resultType->isIntegerType() && !resultType->isPointerType())
15930  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15931  << resultType << Input.get()->getSourceRange());
15932  }
15933  } else if (resultType->isExtVectorType()) {
15934  if (Context.getLangOpts().OpenCL &&
15936  // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15937  // operate on vector float types.
15938  QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15939  if (!T->isIntegerType())
15940  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15941  << resultType << Input.get()->getSourceRange());
15942  }
15943  // Vector logical not returns the signed variant of the operand type.
15944  resultType = GetSignedVectorType(resultType);
15945  break;
15946  } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15947  const VectorType *VTy = resultType->castAs<VectorType>();
15949  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15950  << resultType << Input.get()->getSourceRange());
15951 
15952  // Vector logical not returns the signed variant of the operand type.
15953  resultType = GetSignedVectorType(resultType);
15954  break;
15955  } else {
15956  return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15957  << resultType << Input.get()->getSourceRange());
15958  }
15959 
15960  // LNot always has type int. C99 6.5.3.3p5.
15961  // In C++, it's bool. C++ 5.3.1p8
15962  resultType = Context.getLogicalOperationType();
15963  break;
15964  case UO_Real:
15965  case UO_Imag:
15966  resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15967  // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15968  // complex l-values to ordinary l-values and all other values to r-values.
15969  if (Input.isInvalid()) return ExprError();
15970  if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15971  if (Input.get()->isGLValue() &&
15972  Input.get()->getObjectKind() == OK_Ordinary)
15973  VK = Input.get()->getValueKind();
15974  } else if (!getLangOpts().CPlusPlus) {
15975  // In C, a volatile scalar is read by __imag. In C++, it is not.
15976  Input = DefaultLvalueConversion(Input.get());
15977  }
15978  break;
15979  case UO_Extension:
15980  resultType = Input.get()->getType();
15981  VK = Input.get()->getValueKind();
15982  OK = Input.get()->getObjectKind();
15983  break;
15984  case UO_Coawait:
15985  // It's unnecessary to represent the pass-through operator co_await in the
15986  // AST; just return the input expression instead.
15987  assert(!Input.get()->getType()->isDependentType() &&
15988  "the co_await expression must be non-dependant before "
15989  "building operator co_await");
15990  return Input;
15991  }
15992  if (resultType.isNull() || Input.isInvalid())
15993  return ExprError();
15994 
15995  // Check for array bounds violations in the operand of the UnaryOperator,
15996  // except for the '*' and '&' operators that have to be handled specially
15997  // by CheckArrayAccess (as there are special cases like &array[arraysize]
15998  // that are explicitly defined as valid by the standard).
15999  if (Opc != UO_AddrOf && Opc != UO_Deref)
16000  CheckArrayAccess(Input.get());
16001 
16002  auto *UO =
16003  UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16004  OpLoc, CanOverflow, CurFPFeatureOverrides());
16005 
16006  if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16007  !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16009  ExprEvalContexts.back().PossibleDerefs.insert(UO);
16010 
16011  // Convert the result back to a half vector.
16012  if (ConvertHalfVec)
16013  return convertVector(UO, Context.HalfTy, *this);
16014  return UO;
16015 }
16016 
16017 /// Determine whether the given expression is a qualified member
16018 /// access expression, of a form that could be turned into a pointer to member
16019 /// with the address-of operator.
16021  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16022  if (!DRE->getQualifier())
16023  return false;
16024 
16025  ValueDecl *VD = DRE->getDecl();
16026  if (!VD->isCXXClassMember())
16027  return false;
16028 
16029  if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
16030  return true;
16031  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16032  return Method->isInstance();
16033 
16034  return false;
16035  }
16036 
16037  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16038  if (!ULE->getQualifier())
16039  return false;
16040 
16041  for (NamedDecl *D : ULE->decls()) {
16042  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16043  if (Method->isInstance())
16044  return true;
16045  } else {
16046  // Overload set does not contain methods.
16047  break;
16048  }
16049  }
16050 
16051  return false;
16052  }
16053 
16054  return false;
16055 }
16056 
16058  UnaryOperatorKind Opc, Expr *Input,
16059  bool IsAfterAmp) {
16060  // First things first: handle placeholders so that the
16061  // overloaded-operator check considers the right type.
16062  if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16063  // Increment and decrement of pseudo-object references.
16064  if (pty->getKind() == BuiltinType::PseudoObject &&
16066  return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
16067 
16068  // extension is always a builtin operator.
16069  if (Opc == UO_Extension)
16070  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16071 
16072  // & gets special logic for several kinds of placeholder.
16073  // The builtin code knows what to do.
16074  if (Opc == UO_AddrOf &&
16075  (pty->getKind() == BuiltinType::Overload ||
16076  pty->getKind() == BuiltinType::UnknownAny ||
16077  pty->getKind() == BuiltinType::BoundMember))
16078  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16079 
16080  // Anything else needs to be handled now.
16081  ExprResult Result = CheckPlaceholderExpr(Input);
16082  if (Result.isInvalid()) return ExprError();
16083  Input = Result.get();
16084  }
16085 
16086  if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16088  !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16089  // Find all of the overloaded operators visible from this point.
16090  UnresolvedSet<16> Functions;
16092  if (S && OverOp != OO_None)
16093  LookupOverloadedOperatorName(OverOp, S, Functions);
16094 
16095  return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16096  }
16097 
16098  return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16099 }
16100 
16101 // Unary Operators. 'Tok' is the token for the operator.
16103  Expr *Input, bool IsAfterAmp) {
16104  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16105  IsAfterAmp);
16106 }
16107 
16108 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16110  LabelDecl *TheDecl) {
16111  TheDecl->markUsed(Context);
16112  // Create the AST node. The address of a label always has type 'void*'.
16113  auto *Res = new (Context) AddrLabelExpr(
16114  OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16115 
16116  if (getCurFunction())
16117  getCurFunction()->AddrLabels.push_back(Res);
16118 
16119  return Res;
16120 }
16121 
16124 }
16125 
16127  // Note that function is also called by TreeTransform when leaving a
16128  // StmtExpr scope without rebuilding anything.
16129 
16132 }
16133 
16135  SourceLocation RPLoc) {
16136  return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16137 }
16138 
16140  SourceLocation RPLoc, unsigned TemplateDepth) {
16141  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16142  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16143 
16146  assert(!Cleanup.exprNeedsCleanups() &&
16147  "cleanups within StmtExpr not correctly bound!");
16149 
16150  // FIXME: there are a variety of strange constraints to enforce here, for
16151  // example, it is not possible to goto into a stmt expression apparently.
16152  // More semantic analysis is needed.
16153 
16154  // If there are sub-stmts in the compound stmt, take the type of the last one
16155  // as the type of the stmtexpr.
16156  QualType Ty = Context.VoidTy;
16157  bool StmtExprMayBindToTemp = false;
16158  if (!Compound->body_empty()) {
16159  // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16160  if (const auto *LastStmt =
16161  dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
16162  if (const Expr *Value = LastStmt->getExprStmt()) {
16163  StmtExprMayBindToTemp = true;
16164  Ty = Value->getType();
16165  }
16166  }
16167  }
16168 
16169  // FIXME: Check that expression type is complete/non-abstract; statement
16170  // expressions are not lvalues.
16171  Expr *ResStmtExpr =
16172  new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16173  if (StmtExprMayBindToTemp)
16174  return MaybeBindToTemporary(ResStmtExpr);
16175  return ResStmtExpr;
16176 }
16177 
16179  if (ER.isInvalid())
16180  return ExprError();
16181 
16182  // Do function/array conversion on the last expression, but not
16183  // lvalue-to-rvalue. However, initialize an unqualified type.
16185  if (ER.isInvalid())
16186  return ExprError();
16187  Expr *E = ER.get();
16188 
16189  if (E->isTypeDependent())
16190  return E;
16191 
16192  // In ARC, if the final expression ends in a consume, splice
16193  // the consume out and bind it later. In the alternate case
16194  // (when dealing with a retainable type), the result
16195  // initialization will create a produce. In both cases the
16196  // result will be +1, and we'll need to balance that out with
16197  // a bind.
16198  auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16199  if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16200  return Cast->getSubExpr();
16201 
16202  // FIXME: Provide a better location for the initialization.
16205  E->getBeginLoc(), E->getType().getUnqualifiedType()),
16206  SourceLocation(), E);
16207 }
16208 
16210  TypeSourceInfo *TInfo,
16211  ArrayRef<OffsetOfComponent> Components,
16212  SourceLocation RParenLoc) {
16213  QualType ArgTy = TInfo->getType();
16214  bool Dependent = ArgTy->isDependentType();
16215  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16216 
16217  // We must have at least one component that refers to the type, and the first
16218  // one is known to be a field designator. Verify that the ArgTy represents
16219  // a struct/union/class.
16220  if (!Dependent && !ArgTy->isRecordType())
16221  return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16222  << ArgTy << TypeRange);
16223 
16224  // Type must be complete per C99 7.17p3 because a declaring a variable
16225  // with an incomplete type would be ill-formed.
16226  if (!Dependent
16227  && RequireCompleteType(BuiltinLoc, ArgTy,
16228  diag::err_offsetof_incomplete_type, TypeRange))
16229  return ExprError();
16230 
16231  bool DidWarnAboutNonPOD = false;
16232  QualType CurrentType = ArgTy;
16234  SmallVector<Expr*, 4> Exprs;
16235  for (const OffsetOfComponent &OC : Components) {
16236  if (OC.isBrackets) {
16237  // Offset of an array sub-field. TODO: Should we allow vector elements?
16238  if (!CurrentType->isDependentType()) {
16239  const ArrayType *AT = Context.getAsArrayType(CurrentType);
16240  if(!AT)
16241  return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16242  << CurrentType);
16243  CurrentType = AT->getElementType();
16244  } else
16245  CurrentType = Context.DependentTy;
16246 
16247  ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16248  if (IdxRval.isInvalid())
16249  return ExprError();
16250  Expr *Idx = IdxRval.get();
16251 
16252  // The expression must be an integral expression.
16253  // FIXME: An integral constant expression?
16254  if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16255  !Idx->getType()->isIntegerType())
16256  return ExprError(
16257  Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16258  << Idx->getSourceRange());
16259 
16260  // Record this array index.
16261  Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16262  Exprs.push_back(Idx);
16263  continue;
16264  }
16265 
16266  // Offset of a field.
16267  if (CurrentType->isDependentType()) {
16268  // We have the offset of a field, but we can't look into the dependent
16269  // type. Just record the identifier of the field.
16270  Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16271  CurrentType = Context.DependentTy;
16272  continue;
16273  }
16274 
16275  // We need to have a complete type to look into.
16276  if (RequireCompleteType(OC.LocStart, CurrentType,
16277  diag::err_offsetof_incomplete_type))
16278  return ExprError();
16279 
16280  // Look for the designated field.
16281  const RecordType *RC = CurrentType->getAs<RecordType>();
16282  if (!RC)
16283  return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16284  << CurrentType);
16285  RecordDecl *RD = RC->getDecl();
16286 
16287  // C++ [lib.support.types]p5:
16288  // The macro offsetof accepts a restricted set of type arguments in this
16289  // International Standard. type shall be a POD structure or a POD union
16290  // (clause 9).
16291  // C++11 [support.types]p4:
16292  // If type is not a standard-layout class (Clause 9), the results are
16293  // undefined.
16294  if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16295  bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16296  unsigned DiagID =
16297  LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16298  : diag::ext_offsetof_non_pod_type;
16299 
16300  if (!IsSafe && !DidWarnAboutNonPOD &&
16301  DiagRuntimeBehavior(BuiltinLoc, nullptr,
16302  PDiag(DiagID)
16303  << SourceRange(Components[0].LocStart, OC.LocEnd)
16304  << CurrentType))
16305  DidWarnAboutNonPOD = true;
16306  }
16307 
16308  // Look for the field.
16309  LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16310  LookupQualifiedName(R, RD);
16311  FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16312  IndirectFieldDecl *IndirectMemberDecl = nullptr;
16313  if (!MemberDecl) {
16314  if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16315  MemberDecl = IndirectMemberDecl->getAnonField();
16316  }
16317 
16318  if (!MemberDecl)
16319  return ExprError(Diag(BuiltinLoc, diag::err_no_member)
16320  << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
16321  OC.LocEnd));
16322 
16323  // C99 7.17p3:
16324  // (If the specified member is a bit-field, the behavior is undefined.)
16325  //
16326  // We diagnose this as an error.
16327  if (MemberDecl->isBitField()) {
16328  Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16329  << MemberDecl->getDeclName()
16330  << SourceRange(BuiltinLoc, RParenLoc);
16331  Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16332  return ExprError();
16333  }
16334 
16335  RecordDecl *Parent = MemberDecl->getParent();
16336  if (IndirectMemberDecl)
16337  Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16338 
16339  // If the member was found in a base class, introduce OffsetOfNodes for
16340  // the base class indirections.
16341  CXXBasePaths Paths;
16342  if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16343  Paths)) {
16344  if (Paths.getDetectedVirtual()) {
16345  Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16346  << MemberDecl->getDeclName()
16347  << SourceRange(BuiltinLoc, RParenLoc);
16348  return ExprError();
16349  }
16350 
16351  CXXBasePath &Path = Paths.front();
16352  for (const CXXBasePathElement &B : Path)
16353  Comps.push_back(OffsetOfNode(B.Base));
16354  }
16355 
16356  if (IndirectMemberDecl) {
16357  for (auto *FI : IndirectMemberDecl->chain()) {
16358  assert(isa<FieldDecl>(FI));
16359  Comps.push_back(OffsetOfNode(OC.LocStart,
16360  cast<FieldDecl>(FI), OC.LocEnd));
16361  }
16362  } else
16363  Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16364 
16365  CurrentType = MemberDecl->getType().getNonReferenceType();
16366  }
16367 
16368  return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16369  Comps, Exprs, RParenLoc);
16370 }
16371 
16373  SourceLocation BuiltinLoc,
16375  ParsedType ParsedArgTy,
16376  ArrayRef<OffsetOfComponent> Components,
16377  SourceLocation RParenLoc) {
16378 
16379  TypeSourceInfo *ArgTInfo;
16380  QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16381  if (ArgTy.isNull())
16382  return ExprError();
16383 
16384  if (!ArgTInfo)
16385  ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16386 
16387  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16388 }
16389 
16390 
16392  Expr *CondExpr,
16393  Expr *LHSExpr, Expr *RHSExpr,
16394  SourceLocation RPLoc) {
16395  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16396 
16399  QualType resType;
16400  bool CondIsTrue = false;
16401  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16402  resType = Context.DependentTy;
16403  } else {
16404  // The conditional expression is required to be a constant expression.
16405  llvm::APSInt condEval(32);
16407  CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16408  if (CondICE.isInvalid())
16409  return ExprError();
16410  CondExpr = CondICE.get();
16411  CondIsTrue = condEval.getZExtValue();
16412 
16413  // If the condition is > zero, then the AST type is the same as the LHSExpr.
16414  Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16415 
16416  resType = ActiveExpr->getType();
16417  VK = ActiveExpr->getValueKind();
16418  OK = ActiveExpr->getObjectKind();
16419  }
16420 
16421  return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16422  resType, VK, OK, RPLoc, CondIsTrue);
16423 }
16424 
16425 //===----------------------------------------------------------------------===//
16426 // Clang Extensions.
16427 //===----------------------------------------------------------------------===//
16428 
16429 /// ActOnBlockStart - This callback is invoked when a block literal is started.
16430 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16432 
16433  if (LangOpts.CPlusPlus) {
16434  MangleNumberingContext *MCtx;
16435  Decl *ManglingContextDecl;
16436  std::tie(MCtx, ManglingContextDecl) =
16437  getCurrentMangleNumberContext(Block->getDeclContext());
16438  if (MCtx) {
16439  unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16440  Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16441  }
16442  }
16443 
16444  PushBlockScope(CurScope, Block);
16446  if (CurScope)
16447  PushDeclContext(CurScope, Block);
16448  else
16449  CurContext = Block;
16450 
16452 
16453  // Enter a new evaluation context to insulate the block from any
16454  // cleanups from the enclosing full-expression.
16457 }
16458 
16460  Scope *CurScope) {
16461  assert(ParamInfo.getIdentifier() == nullptr &&
16462  "block-id should have no identifier!");
16463  assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16464  BlockScopeInfo *CurBlock = getCurBlock();
16465 
16466  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16467  QualType T = Sig->getType();
16468 
16469  // FIXME: We should allow unexpanded parameter packs here, but that would,
16470  // in turn, make the block expression contain unexpanded parameter packs.
16471  if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16472  // Drop the parameters.
16474  EPI.HasTrailingReturn = false;
16475  EPI.TypeQuals.addConst();
16476  T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
16478  }
16479 
16480  // GetTypeForDeclarator always produces a function type for a block
16481  // literal signature. Furthermore, it is always a FunctionProtoType
16482  // unless the function was written with a typedef.
16483  assert(T->isFunctionType() &&
16484  "GetTypeForDeclarator made a non-function block signature");
16485 
16486  // Look for an explicit signature in that function type.
16487  FunctionProtoTypeLoc ExplicitSignature;
16488 
16489  if ((ExplicitSignature = Sig->getTypeLoc()
16491 
16492  // Check whether that explicit signature was synthesized by
16493  // GetTypeForDeclarator. If so, don't save that as part of the
16494  // written signature.
16495  if (ExplicitSignature.getLocalRangeBegin() ==
16496  ExplicitSignature.getLocalRangeEnd()) {
16497  // This would be much cheaper if we stored TypeLocs instead of
16498  // TypeSourceInfos.
16499  TypeLoc Result = ExplicitSignature.getReturnLoc();
16500  unsigned Size = Result.getFullDataSize();
16501  Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16502  Sig->getTypeLoc().initializeFullCopy(Result, Size);
16503 
16504  ExplicitSignature = FunctionProtoTypeLoc();
16505  }
16506  }
16507 
16508  CurBlock->TheDecl->setSignatureAsWritten(Sig);
16509  CurBlock->FunctionType = T;
16510 
16511  const auto *Fn = T->castAs<FunctionType>();
16512  QualType RetTy = Fn->getReturnType();
16513  bool isVariadic =
16514  (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16515 
16516  CurBlock->TheDecl->setIsVariadic(isVariadic);
16517 
16518  // Context.DependentTy is used as a placeholder for a missing block
16519  // return type. TODO: what should we do with declarators like:
16520  // ^ * { ... }
16521  // If the answer is "apply template argument deduction"....
16522  if (RetTy != Context.DependentTy) {
16523  CurBlock->ReturnType = RetTy;
16524  CurBlock->TheDecl->setBlockMissingReturnType(false);
16525  CurBlock->HasImplicitReturnType = false;
16526  }
16527 
16528  // Push block parameters from the declarator if we had them.
16530  if (ExplicitSignature) {
16531  for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16532  ParmVarDecl *Param = ExplicitSignature.getParam(I);
16533  if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16534  !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16535  // Diagnose this as an extension in C17 and earlier.
16536  if (!getLangOpts().C2x)
16537  Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
16538  }
16539  Params.push_back(Param);
16540  }
16541 
16542  // Fake up parameter variables if we have a typedef, like
16543  // ^ fntype { ... }
16544  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16545  for (const auto &I : Fn->param_types()) {
16547  CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16548  Params.push_back(Param);
16549  }
16550  }
16551 
16552  // Set the parameters on the block decl.
16553  if (!Params.empty()) {
16554  CurBlock->TheDecl->setParams(Params);
16556  /*CheckParameterNames=*/false);
16557  }
16558 
16559  // Finally we can process decl attributes.
16560  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16561 
16562  // Put the parameter variables in scope.
16563  for (auto *AI : CurBlock->TheDecl->parameters()) {
16564  AI->setOwningFunction(CurBlock->TheDecl);
16565 
16566  // If this has an identifier, add it to the scope stack.
16567  if (AI->getIdentifier()) {
16568  CheckShadow(CurBlock->TheScope, AI);
16569 
16570  PushOnScopeChains(AI, CurBlock->TheScope);
16571  }
16572  }
16573 }
16574 
16575 /// ActOnBlockError - If there is an error parsing a block, this callback
16576 /// is invoked to pop the information about the block from the action impl.
16577 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16578  // Leave the expression-evaluation context.
16581 
16582  // Pop off CurBlock, handle nested blocks.
16583  PopDeclContext();
16585 }
16586 
16587 /// ActOnBlockStmtExpr - This is called when the body of a block statement
16588 /// literal was successfully completed. ^(int x){...}
16590  Stmt *Body, Scope *CurScope) {
16591  // If blocks are disabled, emit an error.
16592  if (!LangOpts.Blocks)
16593  Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16594 
16595  // Leave the expression-evaluation context.
16598  assert(!Cleanup.exprNeedsCleanups() &&
16599  "cleanups within block not correctly bound!");
16601 
16602  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16603  BlockDecl *BD = BSI->TheDecl;
16604 
16605  if (BSI->HasImplicitReturnType)
16607 
16608  QualType RetTy = Context.VoidTy;
16609  if (!BSI->ReturnType.isNull())
16610  RetTy = BSI->ReturnType;
16611 
16612  bool NoReturn = BD->hasAttr<NoReturnAttr>();
16613  QualType BlockTy;
16614 
16615  // If the user wrote a function type in some form, try to use that.
16616  if (!BSI->FunctionType.isNull()) {
16617  const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16618 
16619  FunctionType::ExtInfo Ext = FTy->getExtInfo();
16620  if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16621 
16622  // Turn protoless block types into nullary block types.
16623  if (isa<FunctionNoProtoType>(FTy)) {
16625  EPI.ExtInfo = Ext;
16626  BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16627 
16628  // Otherwise, if we don't need to change anything about the function type,
16629  // preserve its sugar structure.
16630  } else if (FTy->getReturnType() == RetTy &&
16631  (!NoReturn || FTy->getNoReturnAttr())) {
16632  BlockTy = BSI->FunctionType;
16633 
16634  // Otherwise, make the minimal modifications to the function type.
16635  } else {
16636  const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16638  EPI.TypeQuals = Qualifiers();
16639  EPI.ExtInfo = Ext;
16640  BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16641  }
16642 
16643  // If we don't have a function type, just build one from nothing.
16644  } else {
16646  EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16647  BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16648  }
16649 
16651  BlockTy = Context.getBlockPointerType(BlockTy);
16652 
16653  // If needed, diagnose invalid gotos and switches in the block.
16654  if (getCurFunction()->NeedsScopeChecking() &&
16656  DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16657 
16658  BD->setBody(cast<CompoundStmt>(Body));
16659 
16660  if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16662 
16663  // Try to apply the named return value optimization. We have to check again
16664  // if we can do this, though, because blocks keep return statements around
16665  // to deduce an implicit return type.
16666  if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16667  !BD->isDependentContext())
16668  computeNRVO(Body, BSI);
16669 
16674 
16675  PopDeclContext();
16676 
16677  // Set the captured variables on the block.
16679  for (Capture &Cap : BSI->Captures) {
16680  if (Cap.isInvalid() || Cap.isThisCapture())
16681  continue;
16682  // Cap.getVariable() is always a VarDecl because
16683  // blocks cannot capture structured bindings or other ValueDecl kinds.
16684  auto *Var = cast<VarDecl>(Cap.getVariable());
16685  Expr *CopyExpr = nullptr;
16686  if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16687  if (const RecordType *Record =
16688  Cap.getCaptureType()->getAs<RecordType>()) {
16689  // The capture logic needs the destructor, so make sure we mark it.
16690  // Usually this is unnecessary because most local variables have
16691  // their destructors marked at declaration time, but parameters are
16692  // an exception because it's technically only the call site that
16693  // actually requires the destructor.
16694  if (isa<ParmVarDecl>(Var))
16695  FinalizeVarWithDestructor(Var, Record);
16696 
16697  // Enter a separate potentially-evaluated context while building block
16698  // initializers to isolate their cleanups from those of the block
16699  // itself.
16700  // FIXME: Is this appropriate even when the block itself occurs in an
16701  // unevaluated operand?
16704 
16705  SourceLocation Loc = Cap.getLocation();
16706 
16708  CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16709 
16710  // According to the blocks spec, the capture of a variable from
16711  // the stack requires a const copy constructor. This is not true
16712  // of the copy/move done to move a __block variable to the heap.
16713  if (!Result.isInvalid() &&
16714  !Result.get()->getType().isConstQualified()) {
16715  Result = ImpCastExprToType(Result.get(),
16716  Result.get()->getType().withConst(),
16717  CK_NoOp, VK_LValue);
16718  }
16719 
16720  if (!Result.isInvalid()) {
16721  Result = PerformCopyInitialization(
16722  InitializedEntity::InitializeBlock(Var->getLocation(),
16723  Cap.getCaptureType()),
16724  Loc, Result.get());
16725  }
16726 
16727  // Build a full-expression copy expression if initialization
16728  // succeeded and used a non-trivial constructor. Recover from
16729  // errors by pretending that the copy isn't necessary.
16730  if (!Result.isInvalid() &&
16731  !cast<CXXConstructExpr>(Result.get())->getConstructor()
16732  ->isTrivial()) {
16733  Result = MaybeCreateExprWithCleanups(Result);
16734  CopyExpr = Result.get();
16735  }
16736  }
16737  }
16738 
16739  BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16740  CopyExpr);
16741  Captures.push_back(NewCap);
16742  }
16743  BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16744 
16745  // Pop the block scope now but keep it alive to the end of this function.
16747  PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16748 
16749  BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16750 
16751  // If the block isn't obviously global, i.e. it captures anything at
16752  // all, then we need to do a few things in the surrounding context:
16753  if (Result->getBlockDecl()->hasCaptures()) {
16754  // First, this expression has a new cleanup object.
16755  ExprCleanupObjects.push_back(Result->getBlockDecl());
16757 
16758  // It also gets a branch-protected scope if any of the captured
16759  // variables needs destruction.
16760  for (const auto &CI : Result->getBlockDecl()->captures()) {
16761  const VarDecl *var = CI.getVariable();
16762  if (var->getType().isDestructedType() != QualType::DK_none) {
16764  break;
16765  }
16766  }
16767  }
16768 
16769  if (getCurFunction())
16770  getCurFunction()->addBlock(BD);
16771 
16772  return Result;
16773 }
16774 
16776  SourceLocation RPLoc) {
16777  TypeSourceInfo *TInfo;
16778  GetTypeFromParser(Ty, &TInfo);
16779  return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16780 }
16781 
16783  Expr *E, TypeSourceInfo *TInfo,
16784  SourceLocation RPLoc) {
16785  Expr *OrigExpr = E;
16786  bool IsMS = false;
16787 
16788  // CUDA device code does not support varargs.
16789  if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16790  if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16792  if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16793  return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16794  }
16795  }
16796 
16797  // NVPTX does not support va_arg expression.
16798  if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16799  Context.getTargetInfo().getTriple().isNVPTX())
16800  targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16801 
16802  // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16803  // as Microsoft ABI on an actual Microsoft platform, where
16804  // __builtin_ms_va_list and __builtin_va_list are the same.)
16807  QualType MSVaListType = Context.getBuiltinMSVaListType();
16808  if (Context.hasSameType(MSVaListType, E->getType())) {
16809  if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16810  return ExprError();
16811  IsMS = true;
16812  }
16813  }
16814 
16815  // Get the va_list type
16816  QualType VaListType = Context.getBuiltinVaListType();
16817  if (!IsMS) {
16818  if (VaListType->isArrayType()) {
16819  // Deal with implicit array decay; for example, on x86-64,
16820  // va_list is an array, but it's supposed to decay to
16821  // a pointer for va_arg.
16822  VaListType = Context.getArrayDecayedType(VaListType);
16823  // Make sure the input expression also decays appropriately.
16824  ExprResult Result = UsualUnaryConversions(E);
16825  if (Result.isInvalid())
16826  return ExprError();
16827  E = Result.get();
16828  } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16829  // If va_list is a record type and we are compiling in C++ mode,
16830  // check the argument using reference binding.
16832  Context, Context.getLValueReferenceType(VaListType), false);
16834  if (Init.isInvalid())
16835  return ExprError();
16836  E = Init.getAs<Expr>();
16837  } else {
16838  // Otherwise, the va_list argument must be an l-value because
16839  // it is modified by va_arg.
16840  if (!E->isTypeDependent() &&
16841  CheckForModifiableLvalue(E, BuiltinLoc, *this))
16842  return ExprError();
16843  }
16844  }
16845 
16846  if (!IsMS && !E->isTypeDependent() &&
16847  !Context.hasSameType(VaListType, E->getType()))
16848  return ExprError(
16849  Diag(E->getBeginLoc(),
16850  diag::err_first_argument_to_va_arg_not_of_type_va_list)
16851  << OrigExpr->getType() << E->getSourceRange());
16852 
16853  if (!TInfo->getType()->isDependentType()) {
16854  if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16855  diag::err_second_parameter_to_va_arg_incomplete,
16856  TInfo->getTypeLoc()))
16857  return ExprError();
16858 
16860  TInfo->getType(),
16861  diag::err_second_parameter_to_va_arg_abstract,
16862  TInfo->getTypeLoc()))
16863  return ExprError();
16864 
16865  if (!TInfo->getType().isPODType(Context)) {
16866  Diag(TInfo->getTypeLoc().getBeginLoc(),
16867  TInfo->getType()->isObjCLifetimeType()
16868  ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16869  : diag::warn_second_parameter_to_va_arg_not_pod)
16870  << TInfo->getType()
16871  << TInfo->getTypeLoc().getSourceRange();
16872  }
16873 
16874  // Check for va_arg where arguments of the given type will be promoted
16875  // (i.e. this va_arg is guaranteed to have undefined behavior).
16876  QualType PromoteType;
16877  if (Context.isPromotableIntegerType(TInfo->getType())) {
16878  PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16879  // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16880  // and C2x 7.16.1.1p2 says, in part:
16881  // If type is not compatible with the type of the actual next argument
16882  // (as promoted according to the default argument promotions), the
16883  // behavior is undefined, except for the following cases:
16884  // - both types are pointers to qualified or unqualified versions of
16885  // compatible types;
16886  // - one type is a signed integer type, the other type is the
16887  // corresponding unsigned integer type, and the value is
16888  // representable in both types;
16889  // - one type is pointer to qualified or unqualified void and the
16890  // other is a pointer to a qualified or unqualified character type.
16891  // Given that type compatibility is the primary requirement (ignoring
16892  // qualifications), you would think we could call typesAreCompatible()
16893  // directly to test this. However, in C++, that checks for *same type*,
16894  // which causes false positives when passing an enumeration type to
16895  // va_arg. Instead, get the underlying type of the enumeration and pass
16896  // that.
16897  QualType UnderlyingType = TInfo->getType();
16898  if (const auto *ET = UnderlyingType->getAs<EnumType>())
16899  UnderlyingType = ET->getDecl()->getIntegerType();
16900  if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16901  /*CompareUnqualified*/ true))
16902  PromoteType = QualType();
16903 
16904  // If the types are still not compatible, we need to test whether the
16905  // promoted type and the underlying type are the same except for
16906  // signedness. Ask the AST for the correctly corresponding type and see
16907  // if that's compatible.
16908  if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16909  PromoteType->isUnsignedIntegerType() !=
16910  UnderlyingType->isUnsignedIntegerType()) {
16911  UnderlyingType =
16912  UnderlyingType->isUnsignedIntegerType()
16913  ? Context.getCorrespondingSignedType(UnderlyingType)
16914  : Context.getCorrespondingUnsignedType(UnderlyingType);
16915  if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16916  /*CompareUnqualified*/ true))
16917  PromoteType = QualType();
16918  }
16919  }
16921  PromoteType = Context.DoubleTy;
16922  if (!PromoteType.isNull())
16924  PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16925  << TInfo->getType()
16926  << PromoteType
16927  << TInfo->getTypeLoc().getSourceRange());
16928  }
16929 
16931  return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16932 }
16933 
16935  // The type of __null will be int or long, depending on the size of
16936  // pointers on the target.
16937  QualType Ty;
16939  if (pw == Context.getTargetInfo().getIntWidth())
16940  Ty = Context.IntTy;
16941  else if (pw == Context.getTargetInfo().getLongWidth())
16942  Ty = Context.LongTy;
16943  else if (pw == Context.getTargetInfo().getLongLongWidth())
16944  Ty = Context.LongLongTy;
16945  else {
16946  llvm_unreachable("I don't know size of pointer!");
16947  }
16948 
16949  return new (Context) GNUNullExpr(Ty, TokenLoc);
16950 }
16951 
16953  CXXRecordDecl *ImplDecl = nullptr;
16954 
16955  // Fetch the std::source_location::__impl decl.
16956  if (NamespaceDecl *Std = S.getStdNamespace()) {
16957  LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16959  if (S.LookupQualifiedName(ResultSL, Std)) {
16960  if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16961  LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16963  if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16964  S.LookupQualifiedName(ResultImpl, SLDecl)) {
16965  ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16966  }
16967  }
16968  }
16969  }
16970 
16971  if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16972  S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16973  return nullptr;
16974  }
16975 
16976  // Verify that __impl is a trivial struct type, with no base classes, and with
16977  // only the four expected fields.
16978  if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16979  ImplDecl->getNumBases() != 0) {
16980  S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16981  return nullptr;
16982  }
16983 
16984  unsigned Count = 0;
16985  for (FieldDecl *F : ImplDecl->fields()) {
16986  StringRef Name = F->getName();
16987 
16988  if (Name == "_M_file_name") {
16989  if (F->getType() !=
16991  break;
16992  Count++;
16993  } else if (Name == "_M_function_name") {
16994  if (F->getType() !=
16996  break;
16997  Count++;
16998  } else if (Name == "_M_line") {
16999  if (!F->getType()->isIntegerType())
17000  break;
17001  Count++;
17002  } else if (Name == "_M_column") {
17003  if (!F->getType()->isIntegerType())
17004  break;
17005  Count++;
17006  } else {
17007  Count = 100; // invalid
17008  break;
17009  }
17010  }
17011  if (Count != 4) {
17012  S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17013  return nullptr;
17014  }
17015 
17016  return ImplDecl;
17017 }
17018 
17020  SourceLocation BuiltinLoc,
17021  SourceLocation RPLoc) {
17022  QualType ResultTy;
17023  switch (Kind) {
17024  case SourceLocExpr::File:
17025  case SourceLocExpr::Function: {
17027  ResultTy =
17029  break;
17030  }
17031  case SourceLocExpr::Line:
17032  case SourceLocExpr::Column:
17033  ResultTy = Context.UnsignedIntTy;
17034  break;
17038  LookupStdSourceLocationImpl(*this, BuiltinLoc);
17040  return ExprError();
17041  }
17042  ResultTy = Context.getPointerType(
17044  break;
17045  }
17046 
17047  return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17048 }
17049 
17051  QualType ResultTy,
17052  SourceLocation BuiltinLoc,
17053  SourceLocation RPLoc,
17054  DeclContext *ParentContext) {
17055  return new (Context)
17056  SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17057 }
17058 
17060  bool Diagnose) {
17061  if (!getLangOpts().ObjC)
17062  return false;
17063 
17064  const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
17065  if (!PT)
17066  return false;
17067  const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
17068 
17069  // Ignore any parens, implicit casts (should only be
17070  // array-to-pointer decays), and not-so-opaque values. The last is
17071  // important for making this trigger for property assignments.
17072  Expr *SrcExpr = Exp->IgnoreParenImpCasts();
17073  if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
17074  if (OV->getSourceExpr())
17075  SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
17076 
17077  if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
17078  if (!PT->isObjCIdType() &&
17079  !(ID && ID->getIdentifier()->isStr("NSString")))
17080  return false;
17081  if (!SL->isOrdinary())
17082  return false;
17083 
17084  if (Diagnose) {
17085  Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
17086  << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
17087  Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
17088  }
17089  return true;
17090  }
17091 
17092  if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
17093  isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
17094  isa<CXXBoolLiteralExpr>(SrcExpr)) &&
17095  !SrcExpr->isNullPointerConstant(
17097  if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
17098  return false;
17099  if (Diagnose) {
17100  Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
17101  << /*number*/1
17102  << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
17103  Expr *NumLit =
17104  BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
17105  if (NumLit)
17106  Exp = NumLit;
17107  }
17108  return true;
17109  }
17110 
17111  return false;
17112 }
17113 
17115  const Expr *SrcExpr) {
17116  if (!DstType->isFunctionPointerType() ||
17117  !SrcExpr->getType()->isFunctionType())
17118  return false;
17119 
17120  auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17121  if (!DRE)
17122  return false;
17123 
17124  auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17125  if (!FD)
17126  return false;
17127 
17128  return !S.checkAddressOfFunctionIsAvailable(FD,
17129  /*Complain=*/true,
17130  SrcExpr->getBeginLoc());
17131 }
17132 
17134  SourceLocation Loc,
17135  QualType DstType, QualType SrcType,
17136  Expr *SrcExpr, AssignmentAction Action,
17137  bool *Complained) {
17138  if (Complained)
17139  *Complained = false;
17140 
17141  // Decode the result (notice that AST's are still created for extensions).
17142  bool CheckInferredResultType = false;
17143  bool isInvalid = false;
17144  unsigned DiagKind = 0;
17145  ConversionFixItGenerator ConvHints;
17146  bool MayHaveConvFixit = false;
17147  bool MayHaveFunctionDiff = false;
17148  const ObjCInterfaceDecl *IFace = nullptr;
17149  const ObjCProtocolDecl *PDecl = nullptr;
17150 
17151  switch (ConvTy) {
17152  case Compatible:
17153  DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17154  return false;
17155 
17156  case PointerToInt:
17157  if (getLangOpts().CPlusPlus) {
17158  DiagKind = diag::err_typecheck_convert_pointer_int;
17159  isInvalid = true;
17160  } else {
17161  DiagKind = diag::ext_typecheck_convert_pointer_int;
17162  }
17163  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17164  MayHaveConvFixit = true;
17165  break;
17166  case IntToPointer:
17167  if (getLangOpts().CPlusPlus) {
17168  DiagKind = diag::err_typecheck_convert_int_pointer;
17169  isInvalid = true;
17170  } else {
17171  DiagKind = diag::ext_typecheck_convert_int_pointer;
17172  }
17173  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17174  MayHaveConvFixit = true;
17175  break;
17177  DiagKind =
17178  diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17179  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17180  MayHaveConvFixit = true;
17181  break;
17183  if (getLangOpts().CPlusPlus) {
17184  DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17185  isInvalid = true;
17186  } else {
17187  DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17188  }
17189  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17190  MayHaveConvFixit = true;
17191  break;
17192  case IncompatiblePointer:
17193  if (Action == AA_Passing_CFAudited) {
17194  DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17195  } else if (getLangOpts().CPlusPlus) {
17196  DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17197  isInvalid = true;
17198  } else {
17199  DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17200  }
17201  CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17202  SrcType->isObjCObjectPointerType();
17203  if (!CheckInferredResultType) {
17204  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17205  } else if (CheckInferredResultType) {
17206  SrcType = SrcType.getUnqualifiedType();
17207  DstType = DstType.getUnqualifiedType();
17208  }
17209  MayHaveConvFixit = true;
17210  break;
17212  if (getLangOpts().CPlusPlus) {
17213  DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17214  isInvalid = true;
17215  } else {
17216  DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17217  }
17218  break;
17219  case FunctionVoidPointer:
17220  if (getLangOpts().CPlusPlus) {
17221  DiagKind = diag::err_typecheck_convert_pointer_void_func;
17222  isInvalid = true;
17223  } else {
17224  DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17225  }
17226  break;
17228  // Perform array-to-pointer decay if necessary.
17229  if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17230 
17231  isInvalid = true;
17232 
17233  Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17234  Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17235  if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17236  DiagKind = diag::err_typecheck_incompatible_address_space;
17237  break;
17238 
17239  } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17240  DiagKind = diag::err_typecheck_incompatible_ownership;
17241  break;
17242  }
17243 
17244  llvm_unreachable("unknown error case for discarding qualifiers!");
17245  // fallthrough
17246  }
17248  // If the qualifiers lost were because we were applying the
17249  // (deprecated) C++ conversion from a string literal to a char*
17250  // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17251  // Ideally, this check would be performed in
17252  // checkPointerTypesForAssignment. However, that would require a
17253  // bit of refactoring (so that the second argument is an
17254  // expression, rather than a type), which should be done as part
17255  // of a larger effort to fix checkPointerTypesForAssignment for
17256  // C++ semantics.
17257  if (getLangOpts().CPlusPlus &&
17259  return false;
17260  if (getLangOpts().CPlusPlus) {
17261  DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17262  isInvalid = true;
17263  } else {
17264  DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17265  }
17266 
17267  break;
17269  if (getLangOpts().CPlusPlus) {
17270  isInvalid = true;
17271  DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17272  } else {
17273  DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17274  }
17275  break;
17277  DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17278  isInvalid = true;
17279  break;
17280  case IntToBlockPointer:
17281  DiagKind = diag::err_int_to_block_pointer;
17282  isInvalid = true;
17283  break;
17285  DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17286  isInvalid = true;
17287  break;
17289  if (SrcType->isObjCQualifiedIdType()) {
17290  const ObjCObjectPointerType *srcOPT =
17291  SrcType->castAs<ObjCObjectPointerType>();
17292  for (auto *srcProto : srcOPT->quals()) {
17293  PDecl = srcProto;
17294  break;
17295  }
17296  if (const ObjCInterfaceType *IFaceT =
17298  IFace = IFaceT->getDecl();
17299  }
17300  else if (DstType->isObjCQualifiedIdType()) {
17301  const ObjCObjectPointerType *dstOPT =
17302  DstType->castAs<ObjCObjectPointerType>();
17303  for (auto *dstProto : dstOPT->quals()) {
17304  PDecl = dstProto;
17305  break;
17306  }
17307  if (const ObjCInterfaceType *IFaceT =
17309  IFace = IFaceT->getDecl();
17310  }
17311  if (getLangOpts().CPlusPlus) {
17312  DiagKind = diag::err_incompatible_qualified_id;
17313  isInvalid = true;
17314  } else {
17315  DiagKind = diag::warn_incompatible_qualified_id;
17316  }
17317  break;
17318  }
17319  case IncompatibleVectors:
17320  if (getLangOpts().CPlusPlus) {
17321  DiagKind = diag::err_incompatible_vectors;
17322  isInvalid = true;
17323  } else {
17324  DiagKind = diag::warn_incompatible_vectors;
17325  }
17326  break;
17328  DiagKind = diag::err_arc_weak_unavailable_assign;
17329  isInvalid = true;
17330  break;
17331  case Incompatible:
17332  if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17333  if (Complained)
17334  *Complained = true;
17335  return true;
17336  }
17337 
17338  DiagKind = diag::err_typecheck_convert_incompatible;
17339  ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17340  MayHaveConvFixit = true;
17341  isInvalid = true;
17342  MayHaveFunctionDiff = true;
17343  break;
17344  }
17345 
17346  QualType FirstType, SecondType;
17347  switch (Action) {
17348  case AA_Assigning:
17349  case AA_Initializing:
17350  // The destination type comes first.
17351  FirstType = DstType;
17352  SecondType = SrcType;
17353  break;
17354 
17355  case AA_Returning:
17356  case AA_Passing:
17357  case AA_Passing_CFAudited:
17358  case AA_Converting:
17359  case AA_Sending:
17360  case AA_Casting:
17361  // The source type comes first.
17362  FirstType = SrcType;
17363  SecondType = DstType;
17364  break;
17365  }
17366 
17367  PartialDiagnostic FDiag = PDiag(DiagKind);
17368  AssignmentAction ActionForDiag = Action;
17369  if (Action == AA_Passing_CFAudited)
17370  ActionForDiag = AA_Passing;
17371 
17372  FDiag << FirstType << SecondType << ActionForDiag
17373  << SrcExpr->getSourceRange();
17374 
17375  if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17376  DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17377  auto isPlainChar = [](const clang::Type *Type) {
17378  return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17379  Type->isSpecificBuiltinType(BuiltinType::Char_U);
17380  };
17381  FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17382  isPlainChar(SecondType->getPointeeOrArrayElementType()));
17383  }
17384 
17385  // If we can fix the conversion, suggest the FixIts.
17386  if (!ConvHints.isNull()) {
17387  for (FixItHint &H : ConvHints.Hints)
17388  FDiag << H;
17389  }
17390 
17391  if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17392 
17393  if (MayHaveFunctionDiff)
17394  HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17395 
17396  Diag(Loc, FDiag);
17397  if ((DiagKind == diag::warn_incompatible_qualified_id ||
17398  DiagKind == diag::err_incompatible_qualified_id) &&
17399  PDecl && IFace && !IFace->hasDefinition())
17400  Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17401  << IFace << PDecl;
17402 
17403  if (SecondType == Context.OverloadTy)
17405  FirstType, /*TakingAddress=*/true);
17406 
17407  if (CheckInferredResultType)
17408  EmitRelatedResultTypeNote(SrcExpr);
17409 
17410  if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17412 
17413  if (Complained)
17414  *Complained = true;
17415  return isInvalid;
17416 }
17417 
17419  llvm::APSInt *Result,
17420  AllowFoldKind CanFold) {
17421  class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17422  public:
17423  SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17424  QualType T) override {
17425  return S.Diag(Loc, diag::err_ice_not_integral)
17426  << T << S.LangOpts.CPlusPlus;
17427  }
17428  SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17429  return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17430  }
17431  } Diagnoser;
17432 
17433  return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17434 }
17435 
17437  llvm::APSInt *Result,
17438  unsigned DiagID,
17439  AllowFoldKind CanFold) {
17440  class IDDiagnoser : public VerifyICEDiagnoser {
17441  unsigned DiagID;
17442 
17443  public:
17444  IDDiagnoser(unsigned DiagID)
17445  : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17446 
17447  SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17448  return S.Diag(Loc, DiagID);
17449  }
17450  } Diagnoser(DiagID);
17451 
17452  return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17453 }
17454 
17457  QualType T) {
17458  return diagnoseNotICE(S, Loc);
17459 }
17460 
17463  return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17464 }
17465 
17466 ExprResult
17468  VerifyICEDiagnoser &Diagnoser,
17469  AllowFoldKind CanFold) {
17470  SourceLocation DiagLoc = E->getBeginLoc();
17471 
17472  if (getLangOpts().CPlusPlus11) {
17473  // C++11 [expr.const]p5:
17474  // If an expression of literal class type is used in a context where an
17475  // integral constant expression is required, then that class type shall
17476  // have a single non-explicit conversion function to an integral or
17477  // unscoped enumeration type
17478  ExprResult Converted;
17479  class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17480  VerifyICEDiagnoser &BaseDiagnoser;
17481  public:
17482  CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17483  : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17484  BaseDiagnoser.Suppress, true),
17485  BaseDiagnoser(BaseDiagnoser) {}
17486 
17487  SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17488  QualType T) override {
17489  return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17490  }
17491 
17492  SemaDiagnosticBuilder diagnoseIncomplete(
17493  Sema &S, SourceLocation Loc, QualType T) override {
17494  return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17495  }
17496 
17497  SemaDiagnosticBuilder diagnoseExplicitConv(
17498  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17499  return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17500  }
17501 
17502  SemaDiagnosticBuilder noteExplicitConv(
17503  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17504  return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17505  << ConvTy->isEnumeralType() << ConvTy;
17506  }
17507 
17508  SemaDiagnosticBuilder diagnoseAmbiguous(
17509  Sema &S, SourceLocation Loc, QualType T) override {
17510  return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17511  }
17512 
17513  SemaDiagnosticBuilder noteAmbiguous(
17514  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17515  return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17516  << ConvTy->isEnumeralType() << ConvTy;
17517  }
17518 
17519  SemaDiagnosticBuilder diagnoseConversion(
17520  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17521  llvm_unreachable("conversion functions are permitted");
17522  }
17523  } ConvertDiagnoser(Diagnoser);
17524 
17525  Converted = PerformContextualImplicitConversion(DiagLoc, E,
17526  ConvertDiagnoser);
17527  if (Converted.isInvalid())
17528  return Converted;
17529  E = Converted.get();
17531  return ExprError();
17532  } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17533  // An ICE must be of integral or unscoped enumeration type.
17534  if (!Diagnoser.Suppress)
17535  Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17536  << E->getSourceRange();
17537  return ExprError();
17538  }
17539 
17540  ExprResult RValueExpr = DefaultLvalueConversion(E);
17541  if (RValueExpr.isInvalid())
17542  return ExprError();
17543 
17544  E = RValueExpr.get();
17545 
17546  // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17547  // in the non-ICE case.
17549  if (Result)
17551  if (!isa<ConstantExpr>(E))
17552  E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17554  return E;
17555  }
17556 
17557  Expr::EvalResult EvalResult;
17559  EvalResult.Diag = &Notes;
17560 
17561  // Try to evaluate the expression, and produce diagnostics explaining why it's
17562  // not a constant expression as a side-effect.
17563  bool Folded =
17564  E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17565  EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17566 
17567  if (!isa<ConstantExpr>(E))
17568  E = ConstantExpr::Create(Context, E, EvalResult.Val);
17569 
17570  // In C++11, we can rely on diagnostics being produced for any expression
17571  // which is not a constant expression. If no diagnostics were produced, then
17572  // this is a constant expression.
17573  if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17574  if (Result)
17575  *Result = EvalResult.Val.getInt();
17576  return E;
17577  }
17578 
17579  // If our only note is the usual "invalid subexpression" note, just point
17580  // the caret at its location rather than producing an essentially
17581  // redundant note.
17582  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17583  diag::note_invalid_subexpr_in_const_expr) {
17584  DiagLoc = Notes[0].first;
17585  Notes.clear();
17586  }
17587 
17588  if (!Folded || !CanFold) {
17589  if (!Diagnoser.Suppress) {
17590  Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17591  for (const PartialDiagnosticAt &Note : Notes)
17592  Diag(Note.first, Note.second);
17593  }
17594 
17595  return ExprError();
17596  }
17597 
17598  Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17599  for (const PartialDiagnosticAt &Note : Notes)
17600  Diag(Note.first, Note.second);
17601 
17602  if (Result)
17603  *Result = EvalResult.Val.getInt();
17604  return E;
17605 }
17606 
17607 namespace {
17608  // Handle the case where we conclude a expression which we speculatively
17609  // considered to be unevaluated is actually evaluated.
17610  class TransformToPE : public TreeTransform<TransformToPE> {
17611  typedef TreeTransform<TransformToPE> BaseTransform;
17612 
17613  public:
17614  TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17615 
17616  // Make sure we redo semantic analysis
17617  bool AlwaysRebuild() { return true; }
17618  bool ReplacingOriginal() { return true; }
17619 
17620  // We need to special-case DeclRefExprs referring to FieldDecls which
17621  // are not part of a member pointer formation; normal TreeTransforming
17622  // doesn't catch this case because of the way we represent them in the AST.
17623  // FIXME: This is a bit ugly; is it really the best way to handle this
17624  // case?
17625  //
17626  // Error on DeclRefExprs referring to FieldDecls.
17627  ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17628  if (isa<FieldDecl>(E->getDecl()) &&
17629  !SemaRef.isUnevaluatedContext())
17630  return SemaRef.Diag(E->getLocation(),
17631  diag::err_invalid_non_static_member_use)
17632  << E->getDecl() << E->getSourceRange();
17633 
17634  return BaseTransform::TransformDeclRefExpr(E);
17635  }
17636 
17637  // Exception: filter out member pointer formation
17638  ExprResult TransformUnaryOperator(UnaryOperator *E) {
17639  if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17640  return E;
17641 
17642  return BaseTransform::TransformUnaryOperator(E);
17643  }
17644 
17645  // The body of a lambda-expression is in a separate expression evaluation
17646  // context so never needs to be transformed.
17647  // FIXME: Ideally we wouldn't transform the closure type either, and would
17648  // just recreate the capture expressions and lambda expression.
17649  StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17650  return SkipLambdaBody(E, Body);
17651  }
17652  };
17653 }
17654 
17656  assert(isUnevaluatedContext() &&
17657  "Should only transform unevaluated expressions");
17658  ExprEvalContexts.back().Context =
17659  ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17660  if (isUnevaluatedContext())
17661  return E;
17662  return TransformToPE(*this).TransformExpr(E);
17663 }
17664 
17666  assert(isUnevaluatedContext() &&
17667  "Should only transform unevaluated expressions");
17668  ExprEvalContexts.back().Context =
17669  ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17670  if (isUnevaluatedContext())
17671  return TInfo;
17672  return TransformToPE(*this).TransformType(TInfo);
17673 }
17674 
17675 void
17677  ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17679  ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17680  LambdaContextDecl, ExprContext);
17681 
17682  // Discarded statements and immediate contexts nested in other
17683  // discarded statements or immediate context are themselves
17684  // a discarded statement or an immediate context, respectively.
17685  ExprEvalContexts.back().InDiscardedStatement =
17687  .isDiscardedStatementContext();
17688  ExprEvalContexts.back().InImmediateFunctionContext =
17690  .isImmediateFunctionContext();
17691 
17692  Cleanup.reset();
17693  if (!MaybeODRUseExprs.empty())
17694  std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17695 }
17696 
17697 void
17701  Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17702  PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17703 }
17704 
17705 namespace {
17706 
17707 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17708  PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17709  if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17710  if (E->getOpcode() == UO_Deref)
17711  return CheckPossibleDeref(S, E->getSubExpr());
17712  } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17713  return CheckPossibleDeref(S, E->getBase());
17714  } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17715  return CheckPossibleDeref(S, E->getBase());
17716  } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17717  QualType Inner;
17718  QualType Ty = E->getType();
17719  if (const auto *Ptr = Ty->getAs<PointerType>())
17720  Inner = Ptr->getPointeeType();
17721  else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17722  Inner = Arr->getElementType();
17723  else
17724  return nullptr;
17725 
17726  if (Inner->hasAttr(attr::NoDeref))
17727  return E;
17728  }
17729  return nullptr;
17730 }
17731 
17732 } // namespace
17733 
17735  for (const Expr *E : Rec.PossibleDerefs) {
17736  const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17737  if (DeclRef) {
17738  const ValueDecl *Decl = DeclRef->getDecl();
17739  Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17740  << Decl->getName() << E->getSourceRange();
17741  Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17742  } else {
17743  Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17744  << E->getSourceRange();
17745  }
17746  }
17747  Rec.PossibleDerefs.clear();
17748 }
17749 
17750 /// Check whether E, which is either a discarded-value expression or an
17751 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17752 /// and if so, remove it from the list of volatile-qualified assignments that
17753 /// we are going to warn are deprecated.
17756  return;
17757 
17758  // Note: ignoring parens here is not justified by the standard rules, but
17759  // ignoring parentheses seems like a more reasonable approach, and this only
17760  // drives a deprecation warning so doesn't affect conformance.
17761  if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17762  if (BO->getOpcode() == BO_Assign) {
17763  auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17764  llvm::erase_value(LHSs, BO->getLHS());
17765  }
17766  }
17767 }
17768 
17770  if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17771  !Decl->isConsteval() || isConstantEvaluated() ||
17774  return E;
17775 
17776  /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17777  /// It's OK if this fails; we'll also remove this in
17778  /// HandleImmediateInvocations, but catching it here allows us to avoid
17779  /// walking the AST looking for it in simple cases.
17780  if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17781  if (auto *DeclRef =
17782  dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17783  ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17784 
17786 
17788  getASTContext(), E.get(),
17789  ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17790  getASTContext()),
17791  /*IsImmediateInvocation*/ true);
17792  /// Value-dependent constant expressions should not be immediately
17793  /// evaluated until they are instantiated.
17794  if (!Res->isValueDependent())
17795  ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17796  return Res;
17797 }
17798 
17800  Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17802  Expr::EvalResult Eval;
17803  Eval.Diag = &Notes;
17804  ConstantExpr *CE = Candidate.getPointer();
17805  bool Result = CE->EvaluateAsConstantExpr(
17807  if (!Result || !Notes.empty()) {
17808  Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17809  if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17810  InnerExpr = FunctionalCast->getSubExpr();
17811  FunctionDecl *FD = nullptr;
17812  if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17813  FD = cast<FunctionDecl>(Call->getCalleeDecl());
17814  else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17815  FD = Call->getConstructor();
17816  else
17817  llvm_unreachable("unhandled decl kind");
17818  assert(FD && FD->isConsteval());
17819  SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17820  if (auto Context =
17822  SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17823  << Context->Decl;
17824  SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17825  }
17826  for (auto &Note : Notes)
17827  SemaRef.Diag(Note.first, Note.second);
17828  return;
17829  }
17830  CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17831 }
17832 
17836  struct ComplexRemove : TreeTransform<ComplexRemove> {
17838  llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17841  CurrentII;
17842  ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17845  4>::reverse_iterator Current)
17846  : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17847  void RemoveImmediateInvocation(ConstantExpr* E) {
17848  auto It = std::find_if(CurrentII, IISet.rend(),
17850  return Elem.getPointer() == E;
17851  });
17852  assert(It != IISet.rend() &&
17853  "ConstantExpr marked IsImmediateInvocation should "
17854  "be present");
17855  It->setInt(1); // Mark as deleted
17856  }
17857  ExprResult TransformConstantExpr(ConstantExpr *E) {
17858  if (!E->isImmediateInvocation())
17859  return Base::TransformConstantExpr(E);
17860  RemoveImmediateInvocation(E);
17861  return Base::TransformExpr(E->getSubExpr());
17862  }
17863  /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17864  /// we need to remove its DeclRefExpr from the DRSet.
17865  ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17866  DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17867  return Base::TransformCXXOperatorCallExpr(E);
17868  }
17869  /// Base::TransformInitializer skip ConstantExpr so we need to visit them
17870  /// here.
17871  ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17872  if (!Init)
17873  return Init;
17874  /// ConstantExpr are the first layer of implicit node to be removed so if
17875  /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17876  if (auto *CE = dyn_cast<ConstantExpr>(Init))
17877  if (CE->isImmediateInvocation())
17878  RemoveImmediateInvocation(CE);
17879  return Base::TransformInitializer(Init, NotCopyInit);
17880  }
17881  ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17882  DRSet.erase(E);
17883  return E;
17884  }
17885  ExprResult TransformLambdaExpr(LambdaExpr *E) {
17886  // Do not rebuild lambdas to avoid creating a new type.
17887  // Lambdas have already been processed inside their eval context.
17888  return E;
17889  }
17890  bool AlwaysRebuild() { return false; }
17891  bool ReplacingOriginal() { return true; }
17892  bool AllowSkippingCXXConstructExpr() {
17893  bool Res = AllowSkippingFirstCXXConstructExpr;
17894  AllowSkippingFirstCXXConstructExpr = true;
17895  return Res;
17896  }
17897  bool AllowSkippingFirstCXXConstructExpr = true;
17898  } Transformer(SemaRef, Rec.ReferenceToConsteval,
17900 
17901  /// CXXConstructExpr with a single argument are getting skipped by
17902  /// TreeTransform in some situtation because they could be implicit. This
17903  /// can only occur for the top-level CXXConstructExpr because it is used
17904  /// nowhere in the expression being transformed therefore will not be rebuilt.
17905  /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17906  /// skipping the first CXXConstructExpr.
17907  if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17908  Transformer.AllowSkippingFirstCXXConstructExpr = false;
17909 
17910  ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17911  // The result may not be usable in case of previous compilation errors.
17912  // In this case evaluation of the expression may result in crash so just
17913  // don't do anything further with the result.
17914  if (Res.isUsable()) {
17915  Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17916  It->getPointer()->setSubExpr(Res.get());
17917  }
17918 }
17919 
17920 static void
17923  if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17924  Rec.ReferenceToConsteval.size() == 0) ||
17926  return;
17927 
17928  /// When we have more then 1 ImmediateInvocationCandidates we need to check
17929  /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17930  /// need to remove ReferenceToConsteval in the immediate invocation.
17931  if (Rec.ImmediateInvocationCandidates.size() > 1) {
17932 
17933  /// Prevent sema calls during the tree transform from adding pointers that
17934  /// are already in the sets.
17935  llvm::SaveAndRestore DisableIITracking(
17936  SemaRef.RebuildingImmediateInvocation, true);
17937 
17938  /// Prevent diagnostic during tree transfrom as they are duplicates
17939  Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17940 
17941  for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17942  It != Rec.ImmediateInvocationCandidates.rend(); It++)
17943  if (!It->getInt())
17944  RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17945  } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17946  Rec.ReferenceToConsteval.size()) {
17947  struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17948  llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17949  SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17950  bool VisitDeclRefExpr(DeclRefExpr *E) {
17951  DRSet.erase(E);
17952  return DRSet.size();
17953  }
17954  } Visitor(Rec.ReferenceToConsteval);
17955  Visitor.TraverseStmt(
17956  Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17957  }
17958  for (auto CE : Rec.ImmediateInvocationCandidates)
17959  if (!CE.getInt())
17961  for (auto *DR : Rec.ReferenceToConsteval) {
17962  auto *FD = cast<FunctionDecl>(DR->getDecl());
17963  SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17964  << FD;
17965  SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
17966  }
17967 }
17968 
17971  unsigned NumTypos = Rec.NumTypos;
17972 
17973  if (!Rec.Lambdas.empty()) {
17975  if (!getLangOpts().CPlusPlus20 &&
17976  (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17977  Rec.isUnevaluated() ||
17978  (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17979  unsigned D;
17980  if (Rec.isUnevaluated()) {
17981  // C++11 [expr.prim.lambda]p2:
17982  // A lambda-expression shall not appear in an unevaluated operand
17983  // (Clause 5).
17984  D = diag::err_lambda_unevaluated_operand;
17985  } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17986  // C++1y [expr.const]p2:
17987  // A conditional-expression e is a core constant expression unless the
17988  // evaluation of e, following the rules of the abstract machine, would
17989  // evaluate [...] a lambda-expression.
17990  D = diag::err_lambda_in_constant_expression;
17991  } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17992  // C++17 [expr.prim.lamda]p2:
17993  // A lambda-expression shall not appear [...] in a template-argument.
17994  D = diag::err_lambda_in_invalid_context;
17995  } else
17996  llvm_unreachable("Couldn't infer lambda error message.");
17997 
17998  for (const auto *L : Rec.Lambdas)
17999  Diag(L->getBeginLoc(), D);
18000  }
18001  }
18002 
18003  WarnOnPendingNoDerefs(Rec);
18004  HandleImmediateInvocations(*this, Rec);
18005 
18006  // Warn on any volatile-qualified simple-assignments that are not discarded-
18007  // value expressions nor unevaluated operands (those cases get removed from
18008  // this list by CheckUnusedVolatileAssignment).
18009  for (auto *BO : Rec.VolatileAssignmentLHSs)
18010  Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18011  << BO->getType();
18012 
18013  // When are coming out of an unevaluated context, clear out any
18014  // temporaries that we may have created as part of the evaluation of
18015  // the expression in that context: they aren't relevant because they
18016  // will never be constructed.
18017  if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18019  ExprCleanupObjects.end());
18020  Cleanup = Rec.ParentCleanup;
18022  std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
18023  // Otherwise, merge the contexts together.
18024  } else {
18026  MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
18027  Rec.SavedMaybeODRUseExprs.end());
18028  }
18029 
18030  // Pop the current expression evaluation context off the stack.
18031  ExprEvalContexts.pop_back();
18032 
18033  // The global expression evaluation context record is never popped.
18034  ExprEvalContexts.back().NumTypos += NumTypos;
18035 }
18036 
18038  ExprCleanupObjects.erase(
18039  ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18040  ExprCleanupObjects.end());
18041  Cleanup.reset();
18042  MaybeODRUseExprs.clear();
18043 }
18044 
18046  ExprResult Result = CheckPlaceholderExpr(E);
18047  if (Result.isInvalid())
18048  return ExprError();
18049  E = Result.get();
18050  if (!E->getType()->isVariablyModifiedType())
18051  return E;
18053 }
18054 
18055 /// Are we in a context that is potentially constant evaluated per C++20
18056 /// [expr.const]p12?
18058  /// C++2a [expr.const]p12:
18059  // An expression or conversion is potentially constant evaluated if it is
18060  switch (SemaRef.ExprEvalContexts.back().Context) {
18063 
18064  // -- a manifestly constant-evaluated expression,
18068  // -- a potentially-evaluated expression,
18070  // -- an immediate subexpression of a braced-init-list,
18071 
18072  // -- [FIXME] an expression of the form & cast-expression that occurs
18073  // within a templated entity
18074  // -- a subexpression of one of the above that is not a subexpression of
18075  // a nested unevaluated operand.
18076  return true;
18077 
18080  // Expressions in this context are never evaluated.
18081  return false;
18082  }
18083  llvm_unreachable("Invalid context");
18084 }
18085 
18086 /// Return true if this function has a calling convention that requires mangling
18087 /// in the size of the parameter pack.
18089  // These manglings don't do anything on non-Windows or non-x86 platforms, so
18090  // we don't need parameter type sizes.
18091  const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
18092  if (!TT.isOSWindows() || !TT.isX86())
18093  return false;
18094 
18095  // If this is C++ and this isn't an extern "C" function, parameters do not
18096  // need to be complete. In this case, C++ mangling will apply, which doesn't
18097  // use the size of the parameters.
18098  if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18099  return false;
18100 
18101  // Stdcall, fastcall, and vectorcall need this special treatment.
18102  CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18103  switch (CC) {
18104  case CC_X86StdCall:
18105  case CC_X86FastCall:
18106  case CC_X86VectorCall:
18107  return true;
18108  default:
18109  break;
18110  }
18111  return false;
18112 }
18113 
18114 /// Require that all of the parameter types of function be complete. Normally,
18115 /// parameter types are only required to be complete when a function is called
18116 /// or defined, but to mangle functions with certain calling conventions, the
18117 /// mangler needs to know the size of the parameter list. In this situation,
18118 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18119 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18120 /// result in a linker error. Clang doesn't implement this behavior, and instead
18121 /// attempts to error at compile time.
18123  SourceLocation Loc) {
18124  class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18125  FunctionDecl *FD;
18126  ParmVarDecl *Param;
18127 
18128  public:
18129  ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18130  : FD(FD), Param(Param) {}
18131 
18132  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18133  CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18134  StringRef CCName;
18135  switch (CC) {
18136  case CC_X86StdCall:
18137  CCName = "stdcall";
18138  break;
18139  case CC_X86FastCall:
18140  CCName = "fastcall";
18141  break;
18142  case CC_X86VectorCall:
18143  CCName = "vectorcall";
18144  break;
18145  default:
18146  llvm_unreachable("CC does not need mangling");
18147  }
18148 
18149  S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18150  << Param->getDeclName() << FD->getDeclName() << CCName;
18151  }
18152  };
18153 
18154  for (ParmVarDecl *Param : FD->parameters()) {
18155  ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18156  S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18157  }
18158 }
18159 
18160 namespace {
18161 enum class OdrUseContext {
18162  /// Declarations in this context are not odr-used.
18163  None,
18164  /// Declarations in this context are formally odr-used, but this is a
18165  /// dependent context.
18166  Dependent,
18167  /// Declarations in this context are odr-used but not actually used (yet).
18168  FormallyOdrUsed,
18169  /// Declarations in this context are used.
18170  Used
18171 };
18172 }
18173 
18174 /// Are we within a context in which references to resolved functions or to
18175 /// variables result in odr-use?
18176 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18177  OdrUseContext Result;
18178 
18179  switch (SemaRef.ExprEvalContexts.back().Context) {
18183  return OdrUseContext::None;
18184 
18188  Result = OdrUseContext::Used;
18189  break;
18190 
18192  Result = OdrUseContext::FormallyOdrUsed;
18193  break;
18194 
18196  // A default argument formally results in odr-use, but doesn't actually
18197  // result in a use in any real sense until it itself is used.
18198  Result = OdrUseContext::FormallyOdrUsed;
18199  break;
18200  }
18201 
18202  if (SemaRef.CurContext->isDependentContext())
18203  return OdrUseContext::Dependent;
18204 
18205  return Result;
18206 }
18207 
18209  if (!Func->isConstexpr())
18210  return false;
18211 
18212  if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18213  return true;
18214  auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18215  return CCD && CCD->getInheritedConstructor();
18216 }
18217 
18218 /// Mark a function referenced, and check whether it is odr-used
18219 /// (C++ [basic.def.odr]p2, C99 6.9p3)
18221  bool MightBeOdrUse) {
18222  assert(Func && "No function?");
18223 
18224  Func->setReferenced();
18225 
18226  // Recursive functions aren't really used until they're used from some other
18227  // context.
18228  bool IsRecursiveCall = CurContext == Func;
18229 
18230  // C++11 [basic.def.odr]p3:
18231  // A function whose name appears as a potentially-evaluated expression is
18232  // odr-used if it is the unique lookup result or the selected member of a
18233  // set of overloaded functions [...].
18234  //
18235  // We (incorrectly) mark overload resolution as an unevaluated context, so we
18236  // can just check that here.
18237  OdrUseContext OdrUse =
18238  MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18239  if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18240  OdrUse = OdrUseContext::FormallyOdrUsed;
18241 
18242  // Trivial default constructors and destructors are never actually used.
18243  // FIXME: What about other special members?
18244  if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18245  OdrUse == OdrUseContext::Used) {
18246  if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18247  if (Constructor->isDefaultConstructor())
18248  OdrUse = OdrUseContext::FormallyOdrUsed;
18249  if (isa<CXXDestructorDecl>(Func))
18250  OdrUse = OdrUseContext::FormallyOdrUsed;
18251  }
18252 
18253  // C++20 [expr.const]p12:
18254  // A function [...] is needed for constant evaluation if it is [...] a
18255  // constexpr function that is named by an expression that is potentially
18256  // constant evaluated
18257  bool NeededForConstantEvaluation =
18260 
18261  // Determine whether we require a function definition to exist, per
18262  // C++11 [temp.inst]p3:
18263  // Unless a function template specialization has been explicitly
18264  // instantiated or explicitly specialized, the function template
18265  // specialization is implicitly instantiated when the specialization is
18266  // referenced in a context that requires a function definition to exist.
18267  // C++20 [temp.inst]p7:
18268  // The existence of a definition of a [...] function is considered to
18269  // affect the semantics of the program if the [...] function is needed for
18270  // constant evaluation by an expression
18271  // C++20 [basic.def.odr]p10:
18272  // Every program shall contain exactly one definition of every non-inline
18273  // function or variable that is odr-used in that program outside of a
18274  // discarded statement
18275  // C++20 [special]p1:
18276  // The implementation will implicitly define [defaulted special members]
18277  // if they are odr-used or needed for constant evaluation.
18278  //
18279  // Note that we skip the implicit instantiation of templates that are only
18280  // used in unused default arguments or by recursive calls to themselves.
18281  // This is formally non-conforming, but seems reasonable in practice.
18282  bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
18283  NeededForConstantEvaluation);
18284 
18285  // C++14 [temp.expl.spec]p6:
18286  // If a template [...] is explicitly specialized then that specialization
18287  // shall be declared before the first use of that specialization that would
18288  // cause an implicit instantiation to take place, in every translation unit
18289  // in which such a use occurs
18290  if (NeedDefinition &&
18292  Func->getMemberSpecializationInfo()))
18294 
18295  if (getLangOpts().CUDA)
18296  CheckCUDACall(Loc, Func);
18297 
18298  if (getLangOpts().SYCLIsDevice)
18299  checkSYCLDeviceFunction(Loc, Func);
18300 
18301  // If we need a definition, try to create one.
18302  if (NeedDefinition && !Func->getBody()) {
18303  runWithSufficientStackSpace(Loc, [&] {
18304  if (CXXConstructorDecl *Constructor =
18305  dyn_cast<CXXConstructorDecl>(Func)) {
18306  Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18307  if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18308  if (Constructor->isDefaultConstructor()) {
18309  if (Constructor->isTrivial() &&
18310  !Constructor->hasAttr<DLLExportAttr>())
18311  return;
18312  DefineImplicitDefaultConstructor(Loc, Constructor);
18313  } else if (Constructor->isCopyConstructor()) {
18314  DefineImplicitCopyConstructor(Loc, Constructor);
18315  } else if (Constructor->isMoveConstructor()) {
18316  DefineImplicitMoveConstructor(Loc, Constructor);
18317  }
18318  } else if (Constructor->getInheritedConstructor()) {
18319  DefineInheritingConstructor(Loc, Constructor);
18320  }
18321  } else if (CXXDestructorDecl *Destructor =
18322  dyn_cast<CXXDestructorDecl>(Func)) {
18323  Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18324  if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18325  if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18326  return;
18327  DefineImplicitDestructor(Loc, Destructor);
18328  }
18329  if (Destructor->isVirtual() && getLangOpts().AppleKext)
18330  MarkVTableUsed(Loc, Destructor->getParent());
18331  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18332  if (MethodDecl->isOverloadedOperator() &&
18333  MethodDecl->getOverloadedOperator() == OO_Equal) {
18334  MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18335  if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18336  if (MethodDecl->isCopyAssignmentOperator())
18337  DefineImplicitCopyAssignment(Loc, MethodDecl);
18338  else if (MethodDecl->isMoveAssignmentOperator())
18339  DefineImplicitMoveAssignment(Loc, MethodDecl);
18340  }
18341  } else if (isa<CXXConversionDecl>(MethodDecl) &&
18342  MethodDecl->getParent()->isLambda()) {
18343  CXXConversionDecl *Conversion =
18344  cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18345  if (Conversion->isLambdaToBlockPointerConversion())
18347  else
18349  } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18350  MarkVTableUsed(Loc, MethodDecl->getParent());
18351  }
18352 
18353  if (Func->isDefaulted() && !Func->isDeleted()) {
18355  if (DCK != DefaultedComparisonKind::None)
18356  DefineDefaultedComparison(Loc, Func, DCK);
18357  }
18358 
18359  // Implicit instantiation of function templates and member functions of
18360  // class templates.
18361  if (Func->isImplicitlyInstantiable()) {
18364  SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18365  bool FirstInstantiation = PointOfInstantiation.isInvalid();
18366  if (FirstInstantiation) {
18367  PointOfInstantiation = Loc;
18368  if (auto *MSI = Func->getMemberSpecializationInfo())
18369  MSI->setPointOfInstantiation(Loc);
18370  // FIXME: Notify listener.
18371  else
18372  Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18373  } else if (TSK != TSK_ImplicitInstantiation) {
18374  // Use the point of use as the point of instantiation, instead of the
18375  // point of explicit instantiation (which we track as the actual point
18376  // of instantiation). This gives better backtraces in diagnostics.
18377  PointOfInstantiation = Loc;
18378  }
18379 
18380  if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18381  Func->isConstexpr()) {
18382  if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18383  cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18384  CodeSynthesisContexts.size())
18386  std::make_pair(Func, PointOfInstantiation));
18387  else if (Func->isConstexpr())
18388  // Do not defer instantiations of constexpr functions, to avoid the
18389  // expression evaluator needing to call back into Sema if it sees a
18390  // call to such a function.
18391  InstantiateFunctionDefinition(PointOfInstantiation, Func);
18392  else {
18393  Func->setInstantiationIsPending(true);
18394  PendingInstantiations.push_back(
18395  std::make_pair(Func, PointOfInstantiation));
18396  // Notify the consumer that a function was implicitly instantiated.
18398  }
18399  }
18400  } else {
18401  // Walk redefinitions, as some of them may be instantiable.
18402  for (auto *i : Func->redecls()) {
18403  if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18404  MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18405  }
18406  }
18407  });
18408  }
18409 
18410  // If a constructor was defined in the context of a default parameter
18411  // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18412  // context), its initializers may not be referenced yet.
18413  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18414  for (CXXCtorInitializer *Init : Constructor->inits()) {
18415  if (Init->isInClassMemberInitializer())
18416  MarkDeclarationsReferencedInExpr(Init->getInit());
18417  }
18418  }
18419 
18420  // C++14 [except.spec]p17:
18421  // An exception-specification is considered to be needed when:
18422  // - the function is odr-used or, if it appears in an unevaluated operand,
18423  // would be odr-used if the expression were potentially-evaluated;
18424  //
18425  // Note, we do this even if MightBeOdrUse is false. That indicates that the
18426  // function is a pure virtual function we're calling, and in that case the
18427  // function was selected by overload resolution and we need to resolve its
18428  // exception specification for a different reason.
18429  const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18431  ResolveExceptionSpec(Loc, FPT);
18432 
18433  // If this is the first "real" use, act on that.
18434  if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18435  // Keep track of used but undefined functions.
18436  if (!Func->isDefined()) {
18437  if (mightHaveNonExternalLinkage(Func))
18438  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18439  else if (Func->getMostRecentDecl()->isInlined() &&
18440  !LangOpts.GNUInline &&
18441  !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18442  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18443  else if (isExternalWithNoLinkageType(Func))
18444  UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18445  }
18446 
18447  // Some x86 Windows calling conventions mangle the size of the parameter
18448  // pack into the name. Computing the size of the parameters requires the
18449  // parameter types to be complete. Check that now.
18450  if (funcHasParameterSizeMangling(*this, Func))
18451  CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18452 
18453  // In the MS C++ ABI, the compiler emits destructor variants where they are
18454  // used. If the destructor is used here but defined elsewhere, mark the
18455  // virtual base destructors referenced. If those virtual base destructors
18456  // are inline, this will ensure they are defined when emitting the complete
18457  // destructor variant. This checking may be redundant if the destructor is
18458  // provided later in this TU.
18460  if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18461  CXXRecordDecl *Parent = Dtor->getParent();
18462  if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18463  CheckCompleteDestructorVariant(Loc, Dtor);
18464  }
18465  }
18466 
18467  Func->markUsed(Context);
18468  }
18469 }
18470 
18471 /// Directly mark a variable odr-used. Given a choice, prefer to use
18472 /// MarkVariableReferenced since it does additional checks and then
18473 /// calls MarkVarDeclODRUsed.
18474 /// If the variable must be captured:
18475 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18476 /// - else capture it in the DeclContext that maps to the
18477 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18478 static void
18480  const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18481  // Keep track of used but undefined variables.
18482  // FIXME: We shouldn't suppress this warning for static data members.
18483  VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18484  assert(Var && "expected a capturable variable");
18485 
18486  if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18487  (!Var->isExternallyVisible() || Var->isInline() ||
18488  SemaRef.isExternalWithNoLinkageType(Var)) &&
18489  !(Var->isStaticDataMember() && Var->hasInit())) {
18490  SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18491  if (old.isInvalid())
18492  old = Loc;
18493  }
18494  QualType CaptureType, DeclRefType;
18495  if (SemaRef.LangOpts.OpenMP)
18496  SemaRef.tryCaptureOpenMPLambdas(V);
18498  /*EllipsisLoc*/ SourceLocation(),
18499  /*BuildAndDiagnose*/ true, CaptureType,
18500  DeclRefType, FunctionScopeIndexToStopAt);
18501 
18502  if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18503  auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18504  auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
18505  auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
18506  if (VarTarget == Sema::CVT_Host &&
18507  (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
18508  UserTarget == Sema::CFT_Global)) {
18509  // Diagnose ODR-use of host global variables in device functions.
18510  // Reference of device global variables in host functions is allowed
18511  // through shadow variables therefore it is not diagnosed.
18512  if (SemaRef.LangOpts.CUDAIsDevice) {
18513  SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18514  << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18515  SemaRef.targetDiag(Var->getLocation(),
18516  Var->getType().isConstQualified()
18517  ? diag::note_cuda_const_var_unpromoted
18518  : diag::note_cuda_host_var);
18519  }
18520  } else if (VarTarget == Sema::CVT_Device &&
18521  (UserTarget == Sema::CFT_Host ||
18522  UserTarget == Sema::CFT_HostDevice)) {
18523  // Record a CUDA/HIP device side variable if it is ODR-used
18524  // by host code. This is done conservatively, when the variable is
18525  // referenced in any of the following contexts:
18526  // - a non-function context
18527  // - a host function
18528  // - a host device function
18529  // This makes the ODR-use of the device side variable by host code to
18530  // be visible in the device compilation for the compiler to be able to
18531  // emit template variables instantiated by host code only and to
18532  // externalize the static device side variable ODR-used by host code.
18533  if (!Var->hasExternalStorage())
18534  SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18535  else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
18536  SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18537  }
18538  }
18539 
18540  V->markUsed(SemaRef.Context);
18541 }
18542 
18544  SourceLocation Loc,
18545  unsigned CapturingScopeIndex) {
18546  MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18547 }
18548 
18550  ValueDecl *var) {
18551  DeclContext *VarDC = var->getDeclContext();
18552 
18553  // If the parameter still belongs to the translation unit, then
18554  // we're actually just using one parameter in the declaration of
18555  // the next.
18556  if (isa<ParmVarDecl>(var) &&
18557  isa<TranslationUnitDecl>(VarDC))
18558  return;
18559 
18560  // For C code, don't diagnose about capture if we're not actually in code
18561  // right now; it's impossible to write a non-constant expression outside of
18562  // function context, so we'll get other (more useful) diagnostics later.
18563  //
18564  // For C++, things get a bit more nasty... it would be nice to suppress this
18565  // diagnostic for certain cases like using a local variable in an array bound
18566  // for a member of a local class, but the correct predicate is not obvious.
18567  if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18568  return;
18569 
18570  unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18571  unsigned ContextKind = 3; // unknown
18572  if (isa<CXXMethodDecl>(VarDC) &&
18573  cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18574  ContextKind = 2;
18575  } else if (isa<FunctionDecl>(VarDC)) {
18576  ContextKind = 0;
18577  } else if (isa<BlockDecl>(VarDC)) {
18578  ContextKind = 1;
18579  }
18580 
18581  S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18582  << var << ValueKind << ContextKind << VarDC;
18583  S.Diag(var->getLocation(), diag::note_entity_declared_at)
18584  << var;
18585 
18586  // FIXME: Add additional diagnostic info about class etc. which prevents
18587  // capture.
18588 }
18589 
18591  ValueDecl *Var,
18592  bool &SubCapturesAreNested,
18593  QualType &CaptureType,
18594  QualType &DeclRefType) {
18595  // Check whether we've already captured it.
18596  if (CSI->CaptureMap.count(Var)) {
18597  // If we found a capture, any subcaptures are nested.
18598  SubCapturesAreNested = true;
18599 
18600  // Retrieve the capture type for this variable.
18601  CaptureType = CSI->getCapture(Var).getCaptureType();
18602 
18603  // Compute the type of an expression that refers to this variable.
18604  DeclRefType = CaptureType.getNonReferenceType();
18605 
18606  // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18607  // are mutable in the sense that user can change their value - they are
18608  // private instances of the captured declarations.
18609  const Capture &Cap = CSI->getCapture(Var);
18610  if (Cap.isCopyCapture() &&
18611  !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
18612  !(isa<CapturedRegionScopeInfo>(CSI) &&
18613  cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18614  DeclRefType.addConst();
18615  return true;
18616  }
18617  return false;
18618 }
18619 
18620 // Only block literals, captured statements, and lambda expressions can
18621 // capture; other scopes don't work.
18623  ValueDecl *Var,
18624  SourceLocation Loc,
18625  const bool Diagnose,
18626  Sema &S) {
18627  if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18629 
18630  VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18631  if (Underlying) {
18632  if (Underlying->hasLocalStorage() && Diagnose)
18634  }
18635  return nullptr;
18636 }
18637 
18638 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18639 // certain types of variables (unnamed, variably modified types etc.)
18640 // so check for eligibility.
18642  SourceLocation Loc, const bool Diagnose,
18643  Sema &S) {
18644 
18645  assert((isa<VarDecl, BindingDecl>(Var)) &&
18646  "Only variables and structured bindings can be captured");
18647 
18648  bool IsBlock = isa<BlockScopeInfo>(CSI);
18649  bool IsLambda = isa<LambdaScopeInfo>(CSI);
18650 
18651  // Lambdas are not allowed to capture unnamed variables
18652  // (e.g. anonymous unions).
18653  // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18654  // assuming that's the intent.
18655  if (IsLambda && !Var->getDeclName()) {
18656  if (Diagnose) {
18657  S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18658  S.Diag(Var->getLocation(), diag::note_declared_at);
18659  }
18660  return false;
18661  }
18662 
18663  // Prohibit variably-modified types in blocks; they're difficult to deal with.
18664  if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18665  if (Diagnose) {
18666  S.Diag(Loc, diag::err_ref_vm_type);
18667  S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18668  }
18669  return false;
18670  }
18671  // Prohibit structs with flexible array members too.
18672  // We cannot capture what is in the tail end of the struct.
18673  if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18674  if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18675  if (Diagnose) {
18676  if (IsBlock)
18677  S.Diag(Loc, diag::err_ref_flexarray_type);
18678  else
18679  S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18680  S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18681  }
18682  return false;
18683  }
18684  }
18685  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18686  // Lambdas and captured statements are not allowed to capture __block
18687  // variables; they don't support the expected semantics.
18688  if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18689  if (Diagnose) {
18690  S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18691  S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18692  }
18693  return false;
18694  }
18695  // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18696  if (S.getLangOpts().OpenCL && IsBlock &&
18697  Var->getType()->isBlockPointerType()) {
18698  if (Diagnose)
18699  S.Diag(Loc, diag::err_opencl_block_ref_block);
18700  return false;
18701  }
18702 
18703  if (isa<BindingDecl>(Var)) {
18704  if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18705  if (Diagnose)
18707  return false;
18708  } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18709  S.Diag(Loc, S.LangOpts.CPlusPlus20
18710  ? diag::warn_cxx17_compat_capture_binding
18711  : diag::ext_capture_binding)
18712  << Var;
18713  S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18714  }
18715  }
18716 
18717  return true;
18718 }
18719 
18720 // Returns true if the capture by block was successful.
18721 static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
18722  SourceLocation Loc, const bool BuildAndDiagnose,
18723  QualType &CaptureType, QualType &DeclRefType,
18724  const bool Nested, Sema &S, bool Invalid) {
18725  bool ByRef = false;
18726 
18727  // Blocks are not allowed to capture arrays, excepting OpenCL.
18728  // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18729  // (decayed to pointers).
18730  if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18731  if (BuildAndDiagnose) {
18732  S.Diag(Loc, diag::err_ref_array_type);
18733  S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18734  Invalid = true;
18735  } else {
18736  return false;
18737  }
18738  }
18739 
18740  // Forbid the block-capture of autoreleasing variables.
18741  if (!Invalid &&
18743  if (BuildAndDiagnose) {
18744  S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18745  << /*block*/ 0;
18746  S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18747  Invalid = true;
18748  } else {
18749  return false;
18750  }
18751  }
18752 
18753  // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18754  if (const auto *PT = CaptureType->getAs<PointerType>()) {
18755  QualType PointeeTy = PT->getPointeeType();
18756 
18757  if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18759  !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18760  if (BuildAndDiagnose) {
18761  SourceLocation VarLoc = Var->getLocation();
18762  S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18763  S.Diag(VarLoc, diag::note_declare_parameter_strong);
18764  }
18765  }
18766  }
18767 
18768  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18769  if (HasBlocksAttr || CaptureType->isReferenceType() ||
18770  (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
18771  // Block capture by reference does not change the capture or
18772  // declaration reference types.
18773  ByRef = true;
18774  } else {
18775  // Block capture by copy introduces 'const'.
18776  CaptureType = CaptureType.getNonReferenceType().withConst();
18777  DeclRefType = CaptureType;
18778  }
18779 
18780  // Actually capture the variable.
18781  if (BuildAndDiagnose)
18782  BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18783  CaptureType, Invalid);
18784 
18785  return !Invalid;
18786 }
18787 
18788 /// Capture the given variable in the captured region.
18791  const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18792  const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18793  bool IsTopScope, Sema &S, bool Invalid) {
18794  // By default, capture variables by reference.
18795  bool ByRef = true;
18796  if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18797  ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18798  } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18799  // Using an LValue reference type is consistent with Lambdas (see below).
18800  if (S.isOpenMPCapturedDecl(Var)) {
18801  bool HasConst = DeclRefType.isConstQualified();
18802  DeclRefType = DeclRefType.getUnqualifiedType();
18803  // Don't lose diagnostics about assignments to const.
18804  if (HasConst)
18805  DeclRefType.addConst();
18806  }
18807  // Do not capture firstprivates in tasks.
18808  if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
18809  OMPC_unknown)
18810  return true;
18811  ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18812  RSI->OpenMPCaptureLevel);
18813  }
18814 
18815  if (ByRef)
18816  CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18817  else
18818  CaptureType = DeclRefType;
18819 
18820  // Actually capture the variable.
18821  if (BuildAndDiagnose)
18822  RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18823  Loc, SourceLocation(), CaptureType, Invalid);
18824 
18825  return !Invalid;
18826 }
18827 
18828 /// Capture the given variable in the lambda.
18830  SourceLocation Loc, const bool BuildAndDiagnose,
18831  QualType &CaptureType, QualType &DeclRefType,
18832  const bool RefersToCapturedVariable,
18833  const Sema::TryCaptureKind Kind,
18834  SourceLocation EllipsisLoc, const bool IsTopScope,
18835  Sema &S, bool Invalid) {
18836  // Determine whether we are capturing by reference or by value.
18837  bool ByRef = false;
18838  if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18839  ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18840  } else {
18842  }
18843 
18844  BindingDecl *BD = dyn_cast<BindingDecl>(Var);
18845  // FIXME: We should support capturing structured bindings in OpenMP.
18846  if (!Invalid && BD && S.LangOpts.OpenMP) {
18847  if (BuildAndDiagnose) {
18848  S.Diag(Loc, diag::err_capture_binding_openmp) << Var;
18849  S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18850  }
18851  Invalid = true;
18852  }
18853 
18854  // Compute the type of the field that will capture this variable.
18855  if (ByRef) {
18856  // C++11 [expr.prim.lambda]p15:
18857  // An entity is captured by reference if it is implicitly or
18858  // explicitly captured but not captured by copy. It is
18859  // unspecified whether additional unnamed non-static data
18860  // members are declared in the closure type for entities
18861  // captured by reference.
18862  //
18863  // FIXME: It is not clear whether we want to build an lvalue reference
18864  // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18865  // to do the former, while EDG does the latter. Core issue 1249 will
18866  // clarify, but for now we follow GCC because it's a more permissive and
18867  // easily defensible position.
18868  CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18869  } else {
18870  // C++11 [expr.prim.lambda]p14:
18871  // For each entity captured by copy, an unnamed non-static
18872  // data member is declared in the closure type. The
18873  // declaration order of these members is unspecified. The type
18874  // of such a data member is the type of the corresponding
18875  // captured entity if the entity is not a reference to an
18876  // object, or the referenced type otherwise. [Note: If the
18877  // captured entity is a reference to a function, the
18878  // corresponding data member is also a reference to a
18879  // function. - end note ]
18880  if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18881  if (!RefType->getPointeeType()->isFunctionType())
18882  CaptureType = RefType->getPointeeType();
18883  }
18884 
18885  // Forbid the lambda copy-capture of autoreleasing variables.
18886  if (!Invalid &&
18888  if (BuildAndDiagnose) {
18889  S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18890  S.Diag(Var->getLocation(), diag::note_previous_decl)
18891  << Var->getDeclName();
18892  Invalid = true;
18893  } else {
18894  return false;
18895  }
18896  }
18897 
18898  // Make sure that by-copy captures are of a complete and non-abstract type.
18899  if (!Invalid && BuildAndDiagnose) {
18900  if (!CaptureType->isDependentType() &&
18902  Loc, CaptureType,
18903  diag::err_capture_of_incomplete_or_sizeless_type,
18904  Var->getDeclName()))
18905  Invalid = true;
18906  else if (S.RequireNonAbstractType(Loc, CaptureType,
18907  diag::err_capture_of_abstract_type))
18908  Invalid = true;
18909  }
18910  }
18911 
18912  // Compute the type of a reference to this captured variable.
18913  if (ByRef)
18914  DeclRefType = CaptureType.getNonReferenceType();
18915  else {
18916  // C++ [expr.prim.lambda]p5:
18917  // The closure type for a lambda-expression has a public inline
18918  // function call operator [...]. This function call operator is
18919  // declared const (9.3.1) if and only if the lambda-expression's
18920  // parameter-declaration-clause is not followed by mutable.
18921  DeclRefType = CaptureType.getNonReferenceType();
18922  if (!LSI->Mutable && !CaptureType->isReferenceType())
18923  DeclRefType.addConst();
18924  }
18925 
18926  // Add the capture.
18927  if (BuildAndDiagnose)
18928  LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18929  Loc, EllipsisLoc, CaptureType, Invalid);
18930 
18931  return !Invalid;
18932 }
18933 
18935  const ASTContext &Context) {
18936  // Offer a Copy fix even if the type is dependent.
18937  if (Var->getType()->isDependentType())
18938  return true;
18939  QualType T = Var->getType().getNonReferenceType();
18941  return true;
18942  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18943 
18944  if (!(RD = RD->getDefinition()))
18945  return false;
18946  if (RD->hasSimpleCopyConstructor())
18947  return true;
18948  if (RD->hasUserDeclaredCopyConstructor())
18949  for (CXXConstructorDecl *Ctor : RD->ctors())
18950  if (Ctor->isCopyConstructor())
18951  return !Ctor->isDeleted();
18952  }
18953  return false;
18954 }
18955 
18956 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18957 /// default capture. Fixes may be omitted if they aren't allowed by the
18958 /// standard, for example we can't emit a default copy capture fix-it if we
18959 /// already explicitly copy capture capture another variable.
18961  ValueDecl *Var) {
18963  // Don't offer Capture by copy of default capture by copy fixes if Var is
18964  // known not to be copy constructible.
18965  bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18966 
18967  SmallString<32> FixBuffer;
18968  StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18969  if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18970  SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18971  if (ShouldOfferCopyFix) {
18972  // Offer fixes to insert an explicit capture for the variable.
18973  // [] -> [VarName]
18974  // [OtherCapture] -> [OtherCapture, VarName]
18975  FixBuffer.assign({Separator, Var->getName()});
18976  Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18977  << Var << /*value*/ 0
18978  << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18979  }
18980  // As above but capture by reference.
18981  FixBuffer.assign({Separator, "&", Var->getName()});
18982  Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18983  << Var << /*reference*/ 1
18984  << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18985  }
18986 
18987  // Only try to offer default capture if there are no captures excluding this
18988  // and init captures.
18989  // [this]: OK.
18990  // [X = Y]: OK.
18991  // [&A, &B]: Don't offer.
18992  // [A, B]: Don't offer.
18993  if (llvm::any_of(LSI->Captures, [](Capture &C) {
18994  return !C.isThisCapture() && !C.isInitCapture();
18995  }))
18996  return;
18997 
18998  // The default capture specifiers, '=' or '&', must appear first in the
18999  // capture body.
19000  SourceLocation DefaultInsertLoc =
19002 
19003  if (ShouldOfferCopyFix) {
19004  bool CanDefaultCopyCapture = true;
19005  // [=, *this] OK since c++17
19006  // [=, this] OK since c++20
19007  if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19008  CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19009  ? LSI->getCXXThisCapture().isCopyCapture()
19010  : false;
19011  // We can't use default capture by copy if any captures already specified
19012  // capture by copy.
19013  if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19014  return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19015  })) {
19016  FixBuffer.assign({"=", Separator});
19017  Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19018  << /*value*/ 0
19019  << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19020  }
19021  }
19022 
19023  // We can't use default capture by reference if any captures already specified
19024  // capture by reference.
19025  if (llvm::none_of(LSI->Captures, [](Capture &C) {
19026  return !C.isInitCapture() && C.isReferenceCapture() &&
19027  !C.isThisCapture();
19028  })) {
19029  FixBuffer.assign({"&", Separator});
19030  Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19031  << /*reference*/ 1
19032  << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19033  }
19034 }
19035 
19038  SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19039  QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19040  // An init-capture is notionally from the context surrounding its
19041  // declaration, but its parent DC is the lambda class.
19042  DeclContext *VarDC = Var->getDeclContext();
19043  const auto *VD = dyn_cast<VarDecl>(Var);
19044  if (VD) {
19045  if (VD->isInitCapture())
19046  VarDC = VarDC->getParent();
19047  } else {
19048  VD = Var->getPotentiallyDecomposedVarDecl();
19049  }
19050  assert(VD && "Cannot capture a null variable");
19051 
19052  DeclContext *DC = CurContext;
19053  const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19054  ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19055  // We need to sync up the Declaration Context with the
19056  // FunctionScopeIndexToStopAt
19057  if (FunctionScopeIndexToStopAt) {
19058  unsigned FSIndex = FunctionScopes.size() - 1;
19059  while (FSIndex != MaxFunctionScopesIndex) {
19061  --FSIndex;
19062  }
19063  }
19064 
19065 
19066  // If the variable is declared in the current context, there is no need to
19067  // capture it.
19068  if (VarDC == DC) return true;
19069 
19070  // Capture global variables if it is required to use private copy of this
19071  // variable.
19072  bool IsGlobal = !VD->hasLocalStorage();
19073  if (IsGlobal &&
19074  !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19075  MaxFunctionScopesIndex)))
19076  return true;
19077 
19078  if (isa<VarDecl>(Var))
19079  Var = cast<VarDecl>(Var->getCanonicalDecl());
19080 
19081  // Walk up the stack to determine whether we can capture the variable,
19082  // performing the "simple" checks that don't depend on type. We stop when
19083  // we've either hit the declared scope of the variable or find an existing
19084  // capture of that variable. We start from the innermost capturing-entity
19085  // (the DC) and ensure that all intervening capturing-entities
19086  // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19087  // declcontext can either capture the variable or have already captured
19088  // the variable.
19089  CaptureType = Var->getType();
19090  DeclRefType = CaptureType.getNonReferenceType();
19091  bool Nested = false;
19092  bool Explicit = (Kind != TryCapture_Implicit);
19093  unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19094  do {
19095  // Only block literals, captured statements, and lambda expressions can
19096  // capture; other scopes don't work.
19097  DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
19098  ExprLoc,
19099  BuildAndDiagnose,
19100  *this);
19101  // We need to check for the parent *first* because, if we *have*
19102  // private-captured a global variable, we need to recursively capture it in
19103  // intermediate blocks, lambdas, etc.
19104  if (!ParentDC) {
19105  if (IsGlobal) {
19106  FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19107  break;
19108  }
19109  return true;
19110  }
19111 
19112  FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19113  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19114 
19115 
19116  // Check whether we've already captured it.
19117  if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19118  DeclRefType)) {
19119  CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19120  break;
19121  }
19122  // If we are instantiating a generic lambda call operator body,
19123  // we do not want to capture new variables. What was captured
19124  // during either a lambdas transformation or initial parsing
19125  // should be used.
19127  if (BuildAndDiagnose) {
19128  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19130  Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19131  Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19132  Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19133  buildLambdaCaptureFixit(*this, LSI, Var);
19134  } else
19135  diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);
19136  }
19137  return true;
19138  }
19139 
19140  // Try to capture variable-length arrays types.
19141  if (Var->getType()->isVariablyModifiedType()) {
19142  // We're going to walk down into the type and look for VLA
19143  // expressions.
19144  QualType QTy = Var->getType();
19145  if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19146  QTy = PVD->getOriginalType();
19148  }
19149 
19150  if (getLangOpts().OpenMP) {
19151  if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19152  // OpenMP private variables should not be captured in outer scope, so
19153  // just break here. Similarly, global variables that are captured in a
19154  // target region should not be captured outside the scope of the region.
19155  if (RSI->CapRegionKind == CR_OpenMP) {
19156  OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
19157  Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19158  // If the variable is private (i.e. not captured) and has variably
19159  // modified type, we still need to capture the type for correct
19160  // codegen in all regions, associated with the construct. Currently,
19161  // it is captured in the innermost captured region only.
19162  if (IsOpenMPPrivateDecl != OMPC_unknown &&
19163  Var->getType()->isVariablyModifiedType()) {
19164  QualType QTy = Var->getType();
19165  if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19166  QTy = PVD->getOriginalType();
19167  for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
19168  I < E; ++I) {
19169  auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19170  FunctionScopes[FunctionScopesIndex - I]);
19171  assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19172  "Wrong number of captured regions associated with the "
19173  "OpenMP construct.");
19174  captureVariablyModifiedType(Context, QTy, OuterRSI);
19175  }
19176  }
19177  bool IsTargetCap =
19178  IsOpenMPPrivateDecl != OMPC_private &&
19179  isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19180  RSI->OpenMPCaptureLevel);
19181  // Do not capture global if it is not privatized in outer regions.
19182  bool IsGlobalCap =
19183  IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
19184  RSI->OpenMPCaptureLevel);
19185 
19186  // When we detect target captures we are looking from inside the
19187  // target region, therefore we need to propagate the capture from the
19188  // enclosing region. Therefore, the capture is not initially nested.
19189  if (IsTargetCap)
19190  adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
19191 
19192  if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19193  (IsGlobal && !IsGlobalCap)) {
19194  Nested = !IsTargetCap;
19195  bool HasConst = DeclRefType.isConstQualified();
19196  DeclRefType = DeclRefType.getUnqualifiedType();
19197  // Don't lose diagnostics about assignments to const.
19198  if (HasConst)
19199  DeclRefType.addConst();
19200  CaptureType = Context.getLValueReferenceType(DeclRefType);
19201  break;
19202  }
19203  }
19204  }
19205  }
19206  if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19207  // No capture-default, and this is not an explicit capture
19208  // so cannot capture this variable.
19209  if (BuildAndDiagnose) {
19210  Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19211  Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19212  auto *LSI = cast<LambdaScopeInfo>(CSI);
19213  if (LSI->Lambda) {
19214  Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19215  buildLambdaCaptureFixit(*this, LSI, Var);
19216  }
19217  // FIXME: If we error out because an outer lambda can not implicitly
19218  // capture a variable that an inner lambda explicitly captures, we
19219  // should have the inner lambda do the explicit capture - because
19220  // it makes for cleaner diagnostics later. This would purely be done
19221  // so that the diagnostic does not misleadingly claim that a variable
19222  // can not be captured by a lambda implicitly even though it is captured
19223  // explicitly. Suggestion:
19224  // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19225  // at the function head
19226  // - cache the StartingDeclContext - this must be a lambda
19227  // - captureInLambda in the innermost lambda the variable.
19228  }
19229  return true;
19230  }
19231 
19232  FunctionScopesIndex--;
19233  DC = ParentDC;
19234  Explicit = false;
19235  } while (!VarDC->Equals(DC));
19236 
19237  // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19238  // computing the type of the capture at each step, checking type-specific
19239  // requirements, and adding captures if requested.
19240  // If the variable had already been captured previously, we start capturing
19241  // at the lambda nested within that one.
19242  bool Invalid = false;
19243  for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19244  ++I) {
19245  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19246 
19247  // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19248  // certain types of variables (unnamed, variably modified types etc.)
19249  // so check for eligibility.
19250  if (!Invalid)
19251  Invalid =
19252  !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19253 
19254  // After encountering an error, if we're actually supposed to capture, keep
19255  // capturing in nested contexts to suppress any follow-on diagnostics.
19256  if (Invalid && !BuildAndDiagnose)
19257  return true;
19258 
19259  if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19260  Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19261  DeclRefType, Nested, *this, Invalid);
19262  Nested = true;
19263  } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19264  Invalid = !captureInCapturedRegion(
19265  RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19266  Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19267  Nested = true;
19268  } else {
19269  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19270  Invalid =
19271  !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19272  DeclRefType, Nested, Kind, EllipsisLoc,
19273  /*IsTopScope*/ I == N - 1, *this, Invalid);
19274  Nested = true;
19275  }
19276 
19277  if (Invalid && !BuildAndDiagnose)
19278  return true;
19279  }
19280  return Invalid;
19281 }
19282 
19284  TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19285  QualType CaptureType;
19286  QualType DeclRefType;
19287  return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19288  /*BuildAndDiagnose=*/true, CaptureType,
19289  DeclRefType, nullptr);
19290 }
19291 
19293  QualType CaptureType;
19294  QualType DeclRefType;
19296  /*BuildAndDiagnose=*/false, CaptureType,
19297  DeclRefType, nullptr);
19298 }
19299 
19301  QualType CaptureType;
19302  QualType DeclRefType;
19303 
19304  // Determine whether we can capture this variable.
19306  /*BuildAndDiagnose=*/false, CaptureType,
19307  DeclRefType, nullptr))
19308  return QualType();
19309 
19310  return DeclRefType;
19311 }
19312 
19313 namespace {
19314 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19315 // The produced TemplateArgumentListInfo* points to data stored within this
19316 // object, so should only be used in contexts where the pointer will not be
19317 // used after the CopiedTemplateArgs object is destroyed.
19318 class CopiedTemplateArgs {
19319  bool HasArgs;
19320  TemplateArgumentListInfo TemplateArgStorage;
19321 public:
19322  template<typename RefExpr>
19323  CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19324  if (HasArgs)
19325  E->copyTemplateArgumentsInto(TemplateArgStorage);
19326  }
19327  operator TemplateArgumentListInfo*()
19328 #ifdef __has_cpp_attribute
19329 #if __has_cpp_attribute(clang::lifetimebound)
19330  [[clang::lifetimebound]]
19331 #endif
19332 #endif
19333  {
19334  return HasArgs ? &TemplateArgStorage : nullptr;
19335  }
19336 };
19337 }
19338 
19339 /// Walk the set of potential results of an expression and mark them all as
19340 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19341 ///
19342 /// \return A new expression if we found any potential results, ExprEmpty() if
19343 /// not, and ExprError() if we diagnosed an error.
19345  NonOdrUseReason NOUR) {
19346  // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19347  // an object that satisfies the requirements for appearing in a
19348  // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19349  // is immediately applied." This function handles the lvalue-to-rvalue
19350  // conversion part.
19351  //
19352  // If we encounter a node that claims to be an odr-use but shouldn't be, we
19353  // transform it into the relevant kind of non-odr-use node and rebuild the
19354  // tree of nodes leading to it.
19355  //
19356  // This is a mini-TreeTransform that only transforms a restricted subset of
19357  // nodes (and only certain operands of them).
19358 
19359  // Rebuild a subexpression.
19360  auto Rebuild = [&](Expr *Sub) {
19361  return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19362  };
19363 
19364  // Check whether a potential result satisfies the requirements of NOUR.
19365  auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19366  // Any entity other than a VarDecl is always odr-used whenever it's named
19367  // in a potentially-evaluated expression.
19368  auto *VD = dyn_cast<VarDecl>(D);
19369  if (!VD)
19370  return true;
19371 
19372  // C++2a [basic.def.odr]p4:
19373  // A variable x whose name appears as a potentially-evalauted expression
19374  // e is odr-used by e unless
19375  // -- x is a reference that is usable in constant expressions, or
19376  // -- x is a variable of non-reference type that is usable in constant
19377  // expressions and has no mutable subobjects, and e is an element of
19378  // the set of potential results of an expression of
19379  // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19380  // conversion is applied, or
19381  // -- x is a variable of non-reference type, and e is an element of the
19382  // set of potential results of a discarded-value expression to which
19383  // the lvalue-to-rvalue conversion is not applied
19384  //
19385  // We check the first bullet and the "potentially-evaluated" condition in
19386  // BuildDeclRefExpr. We check the type requirements in the second bullet
19387  // in CheckLValueToRValueConversionOperand below.
19388  switch (NOUR) {
19389  case NOUR_None:
19390  case NOUR_Unevaluated:
19391  llvm_unreachable("unexpected non-odr-use-reason");
19392 
19393  case NOUR_Constant:
19394  // Constant references were handled when they were built.
19395  if (VD->getType()->isReferenceType())
19396  return true;
19397  if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19398  if (RD->hasMutableFields())
19399  return true;
19400  if (!VD->isUsableInConstantExpressions(S.Context))
19401  return true;
19402  break;
19403 
19404  case NOUR_Discarded:
19405  if (VD->getType()->isReferenceType())
19406  return true;
19407  break;
19408  }
19409  return false;
19410  };
19411 
19412  // Mark that this expression does not constitute an odr-use.
19413  auto MarkNotOdrUsed = [&] {
19414  S.MaybeODRUseExprs.remove(E);
19415  if (LambdaScopeInfo *LSI = S.getCurLambda())
19416  LSI->markVariableExprAsNonODRUsed(E);
19417  };
19418 
19419  // C++2a [basic.def.odr]p2:
19420  // The set of potential results of an expression e is defined as follows:
19421  switch (E->getStmtClass()) {
19422  // -- If e is an id-expression, ...
19423  case Expr::DeclRefExprClass: {
19424  auto *DRE = cast<DeclRefExpr>(E);
19425  if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19426  break;
19427 
19428  // Rebuild as a non-odr-use DeclRefExpr.
19429  MarkNotOdrUsed();
19430  return DeclRefExpr::Create(
19431  S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19432  DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19433  DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19434  DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19435  }
19436 
19437  case Expr::FunctionParmPackExprClass: {
19438  auto *FPPE = cast<FunctionParmPackExpr>(E);
19439  // If any of the declarations in the pack is odr-used, then the expression
19440  // as a whole constitutes an odr-use.
19441  for (VarDecl *D : *FPPE)
19442  if (IsPotentialResultOdrUsed(D))
19443  return ExprEmpty();
19444 
19445  // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19446  // nothing cares about whether we marked this as an odr-use, but it might
19447  // be useful for non-compiler tools.
19448  MarkNotOdrUsed();
19449  break;
19450  }
19451 
19452  // -- If e is a subscripting operation with an array operand...
19453  case Expr::ArraySubscriptExprClass: {
19454  auto *ASE = cast<ArraySubscriptExpr>(E);
19455  Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19456  if (!OldBase->getType()->isArrayType())
19457  break;
19458  ExprResult Base = Rebuild(OldBase);
19459  if (!Base.isUsable())
19460  return Base;
19461  Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19462  Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19463  SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19464  return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19465  ASE->getRBracketLoc());
19466  }
19467 
19468  case Expr::MemberExprClass: {
19469  auto *ME = cast<MemberExpr>(E);
19470  // -- If e is a class member access expression [...] naming a non-static
19471  // data member...
19472  if (isa<FieldDecl>(ME->getMemberDecl())) {
19473  ExprResult Base = Rebuild(ME->getBase());
19474  if (!Base.isUsable())
19475  return Base;
19476  return MemberExpr::Create(
19477  S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19478  ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19479  ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19480  CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19481  ME->getObjectKind(), ME->isNonOdrUse());
19482  }
19483 
19484  if (ME->getMemberDecl()->isCXXInstanceMember())
19485  break;
19486 
19487  // -- If e is a class member access expression naming a static data member,
19488  // ...
19489  if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19490  break;
19491 
19492  // Rebuild as a non-odr-use MemberExpr.
19493  MarkNotOdrUsed();
19494  return MemberExpr::Create(
19495  S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19496  ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19497  ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19498  ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19499  }
19500 
19501  case Expr::BinaryOperatorClass: {
19502  auto *BO = cast<BinaryOperator>(E);
19503  Expr *LHS = BO->getLHS();
19504  Expr *RHS = BO->getRHS();
19505  // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19506  if (BO->getOpcode() == BO_PtrMemD) {
19507  ExprResult Sub = Rebuild(LHS);
19508  if (!Sub.isUsable())
19509  return Sub;
19510  LHS = Sub.get();
19511  // -- If e is a comma expression, ...
19512  } else if (BO->getOpcode() == BO_Comma) {
19513  ExprResult Sub = Rebuild(RHS);
19514  if (!Sub.isUsable())
19515  return Sub;
19516  RHS = Sub.get();
19517  } else {
19518  break;
19519  }
19520  return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
19521  LHS, RHS);
19522  }
19523 
19524  // -- If e has the form (e1)...
19525  case Expr::ParenExprClass: {
19526  auto *PE = cast<ParenExpr>(E);
19527  ExprResult Sub = Rebuild(PE->getSubExpr());
19528  if (!Sub.isUsable())
19529  return Sub;
19530  return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19531  }
19532 
19533  // -- If e is a glvalue conditional expression, ...
19534  // We don't apply this to a binary conditional operator. FIXME: Should we?
19535  case Expr::ConditionalOperatorClass: {
19536  auto *CO = cast<ConditionalOperator>(E);
19537  ExprResult LHS = Rebuild(CO->getLHS());
19538  if (LHS.isInvalid())
19539  return ExprError();
19540  ExprResult RHS = Rebuild(CO->getRHS());
19541  if (RHS.isInvalid())
19542  return ExprError();
19543  if (!LHS.isUsable() && !RHS.isUsable())
19544  return ExprEmpty();
19545  if (!LHS.isUsable())
19546  LHS = CO->getLHS();
19547  if (!RHS.isUsable())
19548  RHS = CO->getRHS();
19549  return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19550  CO->getCond(), LHS.get(), RHS.get());
19551  }
19552 
19553  // [Clang extension]
19554  // -- If e has the form __extension__ e1...
19555  case Expr::UnaryOperatorClass: {
19556  auto *UO = cast<UnaryOperator>(E);
19557  if (UO->getOpcode() != UO_Extension)
19558  break;
19559  ExprResult Sub = Rebuild(UO->getSubExpr());
19560  if (!Sub.isUsable())
19561  return Sub;
19562  return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19563  Sub.get());
19564  }
19565 
19566  // [Clang extension]
19567  // -- If e has the form _Generic(...), the set of potential results is the
19568  // union of the sets of potential results of the associated expressions.
19569  case Expr::GenericSelectionExprClass: {
19570  auto *GSE = cast<GenericSelectionExpr>(E);
19571 
19572  SmallVector<Expr *, 4> AssocExprs;
19573  bool AnyChanged = false;
19574  for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19575  ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19576  if (AssocExpr.isInvalid())
19577  return ExprError();
19578  if (AssocExpr.isUsable()) {
19579  AssocExprs.push_back(AssocExpr.get());
19580  AnyChanged = true;
19581  } else {
19582  AssocExprs.push_back(OrigAssocExpr);
19583  }
19584  }
19585 
19586  return AnyChanged ? S.CreateGenericSelectionExpr(
19587  GSE->getGenericLoc(), GSE->getDefaultLoc(),
19588  GSE->getRParenLoc(), GSE->getControllingExpr(),
19589  GSE->getAssocTypeSourceInfos(), AssocExprs)
19590  : ExprEmpty();
19591  }
19592 
19593  // [Clang extension]
19594  // -- If e has the form __builtin_choose_expr(...), the set of potential
19595  // results is the union of the sets of potential results of the
19596  // second and third subexpressions.
19597  case Expr::ChooseExprClass: {
19598  auto *CE = cast<ChooseExpr>(E);
19599 
19600  ExprResult LHS = Rebuild(CE->getLHS());
19601  if (LHS.isInvalid())
19602  return ExprError();
19603 
19604  ExprResult RHS = Rebuild(CE->getLHS());
19605  if (RHS.isInvalid())
19606  return ExprError();
19607 
19608  if (!LHS.get() && !RHS.get())
19609  return ExprEmpty();
19610  if (!LHS.isUsable())
19611  LHS = CE->getLHS();
19612  if (!RHS.isUsable())
19613  RHS = CE->getRHS();
19614 
19615  return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19616  RHS.get(), CE->getRParenLoc());
19617  }
19618 
19619  // Step through non-syntactic nodes.
19620  case Expr::ConstantExprClass: {
19621  auto *CE = cast<ConstantExpr>(E);
19622  ExprResult Sub = Rebuild(CE->getSubExpr());
19623  if (!Sub.isUsable())
19624  return Sub;
19625  return ConstantExpr::Create(S.Context, Sub.get());
19626  }
19627 
19628  // We could mostly rely on the recursive rebuilding to rebuild implicit
19629  // casts, but not at the top level, so rebuild them here.
19630  case Expr::ImplicitCastExprClass: {
19631  auto *ICE = cast<ImplicitCastExpr>(E);
19632  // Only step through the narrow set of cast kinds we expect to encounter.
19633  // Anything else suggests we've left the region in which potential results
19634  // can be found.
19635  switch (ICE->getCastKind()) {
19636  case CK_NoOp:
19637  case CK_DerivedToBase:
19638  case CK_UncheckedDerivedToBase: {
19639  ExprResult Sub = Rebuild(ICE->getSubExpr());
19640  if (!Sub.isUsable())
19641  return Sub;
19642  CXXCastPath Path(ICE->path());
19643  return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19644  ICE->getValueKind(), &Path);
19645  }
19646 
19647  default:
19648  break;
19649  }
19650  break;
19651  }
19652 
19653  default:
19654  break;
19655  }
19656 
19657  // Can't traverse through this node. Nothing to do.
19658  return ExprEmpty();
19659 }
19660 
19662  // Check whether the operand is or contains an object of non-trivial C union
19663  // type.
19664  if (E->getType().isVolatileQualified() &&
19670 
19671  // C++2a [basic.def.odr]p4:
19672  // [...] an expression of non-volatile-qualified non-class type to which
19673  // the lvalue-to-rvalue conversion is applied [...]
19674  if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19675  return E;
19676 
19677  ExprResult Result =
19679  if (Result.isInvalid())
19680  return ExprError();
19681  return Result.get() ? Result : E;
19682 }
19683 
19685  Res = CorrectDelayedTyposInExpr(Res);
19686 
19687  if (!Res.isUsable())
19688  return Res;
19689 
19690  // If a constant-expression is a reference to a variable where we delay
19691  // deciding whether it is an odr-use, just assume we will apply the
19692  // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19693  // (a non-type template argument), we have special handling anyway.
19695 }
19696 
19698  // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19699  // call.
19700  MaybeODRUseExprSet LocalMaybeODRUseExprs;
19701  std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19702 
19703  for (Expr *E : LocalMaybeODRUseExprs) {
19704  if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19705  MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19706  DRE->getLocation(), *this);
19707  } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19708  MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19709  *this);
19710  } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19711  for (VarDecl *VD : *FP)
19712  MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19713  } else {
19714  llvm_unreachable("Unexpected expression");
19715  }
19716  }
19717 
19718  assert(MaybeODRUseExprs.empty() &&
19719  "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19720 }
19721 
19722 static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
19723  ValueDecl *Var, Expr *E) {
19725  if (!VD)
19726  return;
19727 
19728  const bool RefersToEnclosingScope =
19729  (SemaRef.CurContext != VD->getDeclContext() &&
19731  if (RefersToEnclosingScope) {
19732  LambdaScopeInfo *const LSI =
19733  SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19734  if (LSI && (!LSI->CallOperator ||
19735  !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19736  // If a variable could potentially be odr-used, defer marking it so
19737  // until we finish analyzing the full expression for any
19738  // lvalue-to-rvalue
19739  // or discarded value conversions that would obviate odr-use.
19740  // Add it to the list of potential captures that will be analyzed
19741  // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19742  // unless the variable is a reference that was initialized by a constant
19743  // expression (this will never need to be captured or odr-used).
19744  //
19745  // FIXME: We can simplify this a lot after implementing P0588R1.
19746  assert(E && "Capture variable should be used in an expression.");
19747  if (!Var->getType()->isReferenceType() ||
19748  !VD->isUsableInConstantExpressions(SemaRef.Context))
19749  LSI->addPotentialCapture(E->IgnoreParens());
19750  }
19751  }
19752 }
19753 
19755  Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19756  llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19757  assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19758  isa<FunctionParmPackExpr>(E)) &&
19759  "Invalid Expr argument to DoMarkVarDeclReferenced");
19760  Var->setReferenced();
19761 
19762  if (Var->isInvalidDecl())
19763  return;
19764 
19765  auto *MSI = Var->getMemberSpecializationInfo();
19768 
19769  OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19770  bool UsableInConstantExpr =
19772 
19773  if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19774  RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19775  }
19776 
19777  // C++20 [expr.const]p12:
19778  // A variable [...] is needed for constant evaluation if it is [...] a
19779  // variable whose name appears as a potentially constant evaluated
19780  // expression that is either a contexpr variable or is of non-volatile
19781  // const-qualified integral type or of reference type
19782  bool NeededForConstantEvaluation =
19783  isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19784 
19785  bool NeedDefinition =
19786  OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19787 
19788  assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19789  "Can't instantiate a partial template specialization.");
19790 
19791  // If this might be a member specialization of a static data member, check
19792  // the specialization is visible. We already did the checks for variable
19793  // template specializations when we created them.
19794  if (NeedDefinition && TSK != TSK_Undeclared &&
19795  !isa<VarTemplateSpecializationDecl>(Var))
19796  SemaRef.checkSpecializationVisibility(Loc, Var);
19797 
19798  // Perform implicit instantiation of static data members, static data member
19799  // templates of class templates, and variable template specializations. Delay
19800  // instantiations of variable templates, except for those that could be used
19801  // in a constant expression.
19802  if (NeedDefinition && isTemplateInstantiation(TSK)) {
19803  // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19804  // instantiation declaration if a variable is usable in a constant
19805  // expression (among other cases).
19806  bool TryInstantiating =
19807  TSK == TSK_ImplicitInstantiation ||
19808  (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19809 
19810  if (TryInstantiating) {
19811  SourceLocation PointOfInstantiation =
19812  MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19813  bool FirstInstantiation = PointOfInstantiation.isInvalid();
19814  if (FirstInstantiation) {
19815  PointOfInstantiation = Loc;
19816  if (MSI)
19817  MSI->setPointOfInstantiation(PointOfInstantiation);
19818  // FIXME: Notify listener.
19819  else
19820  Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19821  }
19822 
19823  if (UsableInConstantExpr) {
19824  // Do not defer instantiations of variables that could be used in a
19825  // constant expression.
19826  SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19827  SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19828  });
19829 
19830  // Re-set the member to trigger a recomputation of the dependence bits
19831  // for the expression.
19832  if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19833  DRE->setDecl(DRE->getDecl());
19834  else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19835  ME->setMemberDecl(ME->getMemberDecl());
19836  } else if (FirstInstantiation ||
19837  isa<VarTemplateSpecializationDecl>(Var)) {
19838  // FIXME: For a specialization of a variable template, we don't
19839  // distinguish between "declaration and type implicitly instantiated"
19840  // and "implicit instantiation of definition requested", so we have
19841  // no direct way to avoid enqueueing the pending instantiation
19842  // multiple times.
19843  SemaRef.PendingInstantiations
19844  .push_back(std::make_pair(Var, PointOfInstantiation));
19845  }
19846  }
19847  }
19848 
19849  // C++2a [basic.def.odr]p4:
19850  // A variable x whose name appears as a potentially-evaluated expression e
19851  // is odr-used by e unless
19852  // -- x is a reference that is usable in constant expressions
19853  // -- x is a variable of non-reference type that is usable in constant
19854  // expressions and has no mutable subobjects [FIXME], and e is an
19855  // element of the set of potential results of an expression of
19856  // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19857  // conversion is applied
19858  // -- x is a variable of non-reference type, and e is an element of the set
19859  // of potential results of a discarded-value expression to which the
19860  // lvalue-to-rvalue conversion is not applied [FIXME]
19861  //
19862  // We check the first part of the second bullet here, and
19863  // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19864  // FIXME: To get the third bullet right, we need to delay this even for
19865  // variables that are not usable in constant expressions.
19866 
19867  // If we already know this isn't an odr-use, there's nothing more to do.
19868  if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19869  if (DRE->isNonOdrUse())
19870  return;
19871  if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19872  if (ME->isNonOdrUse())
19873  return;
19874 
19875  switch (OdrUse) {
19876  case OdrUseContext::None:
19877  // In some cases, a variable may not have been marked unevaluated, if it
19878  // appears in a defaukt initializer.
19879  assert((!E || isa<FunctionParmPackExpr>(E) ||
19880  SemaRef.isUnevaluatedContext()) &&
19881  "missing non-odr-use marking for unevaluated decl ref");
19882  break;
19883 
19884  case OdrUseContext::FormallyOdrUsed:
19885  // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19886  // behavior.
19887  break;
19888 
19889  case OdrUseContext::Used:
19890  // If we might later find that this expression isn't actually an odr-use,
19891  // delay the marking.
19892  if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19893  SemaRef.MaybeODRUseExprs.insert(E);
19894  else
19895  MarkVarDeclODRUsed(Var, Loc, SemaRef);
19896  break;
19897 
19898  case OdrUseContext::Dependent:
19899  // If this is a dependent context, we don't need to mark variables as
19900  // odr-used, but we may still need to track them for lambda capture.
19901  // FIXME: Do we also need to do this inside dependent typeid expressions
19902  // (which are modeled as unevaluated at this point)?
19903  DoMarkPotentialCapture(SemaRef, Loc, Var, E);
19904  break;
19905  }
19906 }
19907 
19909  BindingDecl *BD, Expr *E) {
19910  BD->setReferenced();
19911 
19912  if (BD->isInvalidDecl())
19913  return;
19914 
19915  OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19916  if (OdrUse == OdrUseContext::Used) {
19917  QualType CaptureType, DeclRefType;
19919  /*EllipsisLoc*/ SourceLocation(),
19920  /*BuildAndDiagnose*/ true, CaptureType,
19921  DeclRefType,
19922  /*FunctionScopeIndexToStopAt*/ nullptr);
19923  } else if (OdrUse == OdrUseContext::Dependent) {
19924  DoMarkPotentialCapture(SemaRef, Loc, BD, E);
19925  }
19926 }
19927 
19928 /// Mark a variable referenced, and check whether it is odr-used
19929 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
19930 /// used directly for normal expressions referring to VarDecl.
19932  DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19933 }
19934 
19935 static void
19937  bool MightBeOdrUse,
19938  llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19939  if (SemaRef.isInOpenMPDeclareTargetContext())
19940  SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
19941 
19942  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19943  DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
19944  return;
19945  }
19946 
19947  if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
19948  DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);
19949  return;
19950  }
19951 
19952  SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19953 
19954  // If this is a call to a method via a cast, also mark the method in the
19955  // derived class used in case codegen can devirtualize the call.
19956  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19957  if (!ME)
19958  return;
19959  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19960  if (!MD)
19961  return;
19962  // Only attempt to devirtualize if this is truly a virtual call.
19963  bool IsVirtualCall = MD->isVirtual() &&
19964  ME->performsVirtualDispatch(SemaRef.getLangOpts());
19965  if (!IsVirtualCall)
19966  return;
19967 
19968  // If it's possible to devirtualize the call, mark the called function
19969  // referenced.
19971  ME->getBase(), SemaRef.getLangOpts().AppleKext);
19972  if (DM)
19973  SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19974 }
19975 
19976 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
19977 ///
19978 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19979 /// handled with care if the DeclRefExpr is not newly-created.
19981  // TODO: update this with DR# once a defect report is filed.
19982  // C++11 defect. The address of a pure member should not be an ODR use, even
19983  // if it's a qualified reference.
19984  bool OdrUse = true;
19985  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19986  if (Method->isVirtual() &&
19987  !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19988  OdrUse = false;
19989 
19990  if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
19993  !isCheckingDefaultArgumentOrInitializer() && FD->isConsteval() &&
19994  !RebuildingImmediateInvocation && !FD->isDependentContext())
19995  ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19996  MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19998 }
19999 
20000 /// Perform reference-marking and odr-use handling for a MemberExpr.
20002  // C++11 [basic.def.odr]p2:
20003  // A non-overloaded function whose name appears as a potentially-evaluated
20004  // expression or a member of a set of candidate functions, if selected by
20005  // overload resolution when referred to from a potentially-evaluated
20006  // expression, is odr-used, unless it is a pure virtual function and its
20007  // name is not explicitly qualified.
20008  bool MightBeOdrUse = true;
20010  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20011  if (Method->isPure())
20012  MightBeOdrUse = false;
20013  }
20014  SourceLocation Loc =
20015  E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20016  MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20018 }
20019 
20020 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20022  for (VarDecl *VD : *E)
20023  MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20025 }
20026 
20027 /// Perform marking for a reference to an arbitrary declaration. It
20028 /// marks the declaration referenced, and performs odr-use checking for
20029 /// functions and variables. This method should not be used when building a
20030 /// normal expression which refers to a variable.
20032  bool MightBeOdrUse) {
20033  if (MightBeOdrUse) {
20034  if (auto *VD = dyn_cast<VarDecl>(D)) {
20035  MarkVariableReferenced(Loc, VD);
20036  return;
20037  }
20038  }
20039  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20040  MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20041  return;
20042  }
20043  D->setReferenced();
20044 }
20045 
20046 namespace {
20047  // Mark all of the declarations used by a type as referenced.
20048  // FIXME: Not fully implemented yet! We need to have a better understanding
20049  // of when we're entering a context we should not recurse into.
20050  // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20051  // TreeTransforms rebuilding the type in a new context. Rather than
20052  // duplicating the TreeTransform logic, we should consider reusing it here.
20053  // Currently that causes problems when rebuilding LambdaExprs.
20054  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
20055  Sema &S;
20056  SourceLocation Loc;
20057 
20058  public:
20059  typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
20060 
20061  MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
20062 
20063  bool TraverseTemplateArgument(const TemplateArgument &Arg);
20064  };
20065 }
20066 
20067 bool MarkReferencedDecls::TraverseTemplateArgument(
20068  const TemplateArgument &Arg) {
20069  {
20070  // A non-type template argument is a constant-evaluated context.
20073  if (Arg.getKind() == TemplateArgument::Declaration) {
20074  if (Decl *D = Arg.getAsDecl())
20075  S.MarkAnyDeclReferenced(Loc, D, true);
20076  } else if (Arg.getKind() == TemplateArgument::Expression) {
20078  }
20079  }
20080 
20081  return Inherited::TraverseTemplateArgument(Arg);
20082 }
20083 
20085  MarkReferencedDecls Marker(*this, Loc);
20086  Marker.TraverseType(T);
20087 }
20088 
20089 namespace {
20090 /// Helper class that marks all of the declarations referenced by
20091 /// potentially-evaluated subexpressions as "referenced".
20092 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20093 public:
20094  typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20095  bool SkipLocalVariables;
20096  ArrayRef<const Expr *> StopAt;
20097 
20098  EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20099  ArrayRef<const Expr *> StopAt)
20100  : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20101 
20102  void visitUsedDecl(SourceLocation Loc, Decl *D) {
20103  S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20104  }
20105 
20106  void Visit(Expr *E) {
20107  if (llvm::is_contained(StopAt, E))
20108  return;
20109  Inherited::Visit(E);
20110  }
20111 
20112  void VisitConstantExpr(ConstantExpr *E) {
20113  // Don't mark declarations within a ConstantExpression, as this expression
20114  // will be evaluated and folded to a value.
20115  }
20116 
20117  void VisitDeclRefExpr(DeclRefExpr *E) {
20118  // If we were asked not to visit local variables, don't.
20119  if (SkipLocalVariables) {
20120  if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20121  if (VD->hasLocalStorage())
20122  return;
20123  }
20124 
20125  // FIXME: This can trigger the instantiation of the initializer of a
20126  // variable, which can cause the expression to become value-dependent
20127  // or error-dependent. Do we need to propagate the new dependence bits?
20128  S.MarkDeclRefReferenced(E);
20129  }
20130 
20131  void VisitMemberExpr(MemberExpr *E) {
20132  S.MarkMemberReferenced(E);
20133  Visit(E->getBase());
20134  }
20135 };
20136 } // namespace
20137 
20138 /// Mark any declarations that appear within this expression or any
20139 /// potentially-evaluated subexpressions as "referenced".
20140 ///
20141 /// \param SkipLocalVariables If true, don't mark local variables as
20142 /// 'referenced'.
20143 /// \param StopAt Subexpressions that we shouldn't recurse into.
20145  bool SkipLocalVariables,
20146  ArrayRef<const Expr*> StopAt) {
20147  EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20148 }
20149 
20150 /// Emit a diagnostic when statements are reachable.
20151 /// FIXME: check for reachability even in expressions for which we don't build a
20152 /// CFG (eg, in the initializer of a global or in a constant expression).
20153 /// For example,
20154 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20156  const PartialDiagnostic &PD) {
20157  if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20158  if (!FunctionScopes.empty())
20159  FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20160  sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20161  return true;
20162  }
20163 
20164  // The initializer of a constexpr variable or of the first declaration of a
20165  // static data member is not syntactically a constant evaluated constant,
20166  // but nonetheless is always required to be a constant expression, so we
20167  // can skip diagnosing.
20168  // FIXME: Using the mangling context here is a hack.
20169  if (auto *VD = dyn_cast_or_null<VarDecl>(
20170  ExprEvalContexts.back().ManglingContextDecl)) {
20171  if (VD->isConstexpr() ||
20172  (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20173  return false;
20174  // FIXME: For any other kind of variable, we should build a CFG for its
20175  // initializer and check whether the context in question is reachable.
20176  }
20177 
20178  Diag(Loc, PD);
20179  return true;
20180 }
20181 
20182 /// Emit a diagnostic that describes an effect on the run-time behavior
20183 /// of the program being compiled.
20184 ///
20185 /// This routine emits the given diagnostic when the code currently being
20186 /// type-checked is "potentially evaluated", meaning that there is a
20187 /// possibility that the code will actually be executable. Code in sizeof()
20188 /// expressions, code used only during overload resolution, etc., are not
20189 /// potentially evaluated. This routine will suppress such diagnostics or,
20190 /// in the absolutely nutty case of potentially potentially evaluated
20191 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
20192 /// later.
20193 ///
20194 /// This routine should be used for all diagnostics that describe the run-time
20195 /// behavior of a program, such as passing a non-POD value through an ellipsis.
20196 /// Failure to do so will likely result in spurious diagnostics or failures
20197 /// during overload resolution or within sizeof/alignof/typeof/typeid.
20199  const PartialDiagnostic &PD) {
20200 
20201  if (ExprEvalContexts.back().isDiscardedStatementContext())
20202  return false;
20203 
20204  switch (ExprEvalContexts.back().Context) {
20209  // The argument will never be evaluated, so don't complain.
20210  break;
20211 
20214  // Relevant diagnostics should be produced by constant evaluation.
20215  break;
20216 
20219  return DiagIfReachable(Loc, Stmts, PD);
20220  }
20221 
20222  return false;
20223 }
20224 
20225 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
20226  const PartialDiagnostic &PD) {
20227  return DiagRuntimeBehavior(
20228  Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20229 }
20230 
20232  CallExpr *CE, FunctionDecl *FD) {
20233  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20234  return false;
20235 
20236  // If we're inside a decltype's expression, don't check for a valid return
20237  // type or construct temporaries until we know whether this is the last call.
20238  if (ExprEvalContexts.back().ExprContext ==
20240  ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20241  return false;
20242  }
20243 
20244  class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20245  FunctionDecl *FD;
20246  CallExpr *CE;
20247 
20248  public:
20249  CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20250  : FD(FD), CE(CE) { }
20251 
20252  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20253  if (!FD) {
20254  S.Diag(Loc, diag::err_call_incomplete_return)
20255  << T << CE->getSourceRange();
20256  return;
20257  }
20258 
20259  S.Diag(Loc, diag::err_call_function_incomplete_return)
20260  << CE->getSourceRange() << FD << T;
20261  S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20262  << FD->getDeclName();
20263  }
20264  } Diagnoser(FD, CE);
20265 
20266  if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20267  return true;
20268 
20269  return false;
20270 }
20271 
20272 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20273 // will prevent this condition from triggering, which is what we want.
20275  SourceLocation Loc;
20276 
20277  unsigned diagnostic = diag::warn_condition_is_assignment;
20278  bool IsOrAssign = false;
20279 
20280  if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20281  if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20282  return;
20283 
20284  IsOrAssign = Op->getOpcode() == BO_OrAssign;
20285 
20286  // Greylist some idioms by putting them into a warning subcategory.
20287  if (ObjCMessageExpr *ME
20288  = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20289  Selector Sel = ME->getSelector();
20290 
20291  // self = [<foo> init...]
20292  if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20293  diagnostic = diag::warn_condition_is_idiomatic_assignment;
20294 
20295  // <foo> = [<bar> nextObject]
20296  else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20297  diagnostic = diag::warn_condition_is_idiomatic_assignment;
20298  }
20299 
20300  Loc = Op->getOperatorLoc();
20301  } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20302  if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20303  return;
20304 
20305  IsOrAssign = Op->getOperator() == OO_PipeEqual;
20306  Loc = Op->getOperatorLoc();
20307  } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20308  return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20309  else {
20310  // Not an assignment.
20311  return;
20312  }
20313 
20314  Diag(Loc, diagnostic) << E->getSourceRange();
20315 
20316  SourceLocation Open = E->getBeginLoc();
20318  Diag(Loc, diag::note_condition_assign_silence)
20319  << FixItHint::CreateInsertion(Open, "(")
20320  << FixItHint::CreateInsertion(Close, ")");
20321 
20322  if (IsOrAssign)
20323  Diag(Loc, diag::note_condition_or_assign_to_comparison)
20324  << FixItHint::CreateReplacement(Loc, "!=");
20325  else
20326  Diag(Loc, diag::note_condition_assign_to_comparison)
20327  << FixItHint::CreateReplacement(Loc, "==");
20328 }
20329 
20330 /// Redundant parentheses over an equality comparison can indicate
20331 /// that the user intended an assignment used as condition.
20333  // Don't warn if the parens came from a macro.
20334  SourceLocation parenLoc = ParenE->getBeginLoc();
20335  if (parenLoc.isInvalid() || parenLoc.isMacroID())
20336  return;
20337  // Don't warn for dependent expressions.
20338  if (ParenE->isTypeDependent())
20339  return;
20340 
20341  Expr *E = ParenE->IgnoreParens();
20342 
20343  if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20344  if (opE->getOpcode() == BO_EQ &&
20345  opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20346  == Expr::MLV_Valid) {
20347  SourceLocation Loc = opE->getOperatorLoc();
20348 
20349  Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20350  SourceRange ParenERange = ParenE->getSourceRange();
20351  Diag(Loc, diag::note_equality_comparison_silence)
20352  << FixItHint::CreateRemoval(ParenERange.getBegin())
20353  << FixItHint::CreateRemoval(ParenERange.getEnd());
20354  Diag(Loc, diag::note_equality_comparison_to_assign)
20355  << FixItHint::CreateReplacement(Loc, "=");
20356  }
20357 }
20358 
20360  bool IsConstexpr) {
20362  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20364 
20365  ExprResult result = CheckPlaceholderExpr(E);
20366  if (result.isInvalid()) return ExprError();
20367  E = result.get();
20368 
20369  if (!E->isTypeDependent()) {
20370  if (getLangOpts().CPlusPlus)
20371  return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20372 
20374  if (ERes.isInvalid())
20375  return ExprError();
20376  E = ERes.get();
20377 
20378  QualType T = E->getType();
20379  if (!T->isScalarType()) { // C99 6.8.4.1p1
20380  Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20381  << T << E->getSourceRange();
20382  return ExprError();
20383  }
20384  CheckBoolLikeConversion(E, Loc);
20385  }
20386 
20387  return E;
20388 }
20389 
20391  Expr *SubExpr, ConditionKind CK,
20392  bool MissingOK) {
20393  // MissingOK indicates whether having no condition expression is valid
20394  // (for loop) or invalid (e.g. while loop).
20395  if (!SubExpr)
20396  return MissingOK ? ConditionResult() : ConditionError();
20397 
20398  ExprResult Cond;
20399  switch (CK) {
20401  Cond = CheckBooleanCondition(Loc, SubExpr);
20402  break;
20403 
20405  Cond = CheckBooleanCondition(Loc, SubExpr, true);
20406  break;
20407 
20408  case ConditionKind::Switch:
20409  Cond = CheckSwitchCondition(Loc, SubExpr);
20410  break;
20411  }
20412  if (Cond.isInvalid()) {
20413  Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20414  {SubExpr}, PreferredConditionType(CK));
20415  if (!Cond.get())
20416  return ConditionError();
20417  }
20418  // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20419  FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
20420  if (!FullExpr.get())
20421  return ConditionError();
20422 
20423  return ConditionResult(*this, nullptr, FullExpr,
20425 }
20426 
20427 namespace {
20428  /// A visitor for rebuilding a call to an __unknown_any expression
20429  /// to have an appropriate type.
20430  struct RebuildUnknownAnyFunction
20431  : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20432 
20433  Sema &S;
20434 
20435  RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20436 
20437  ExprResult VisitStmt(Stmt *S) {
20438  llvm_unreachable("unexpected statement!");
20439  }
20440 
20441  ExprResult VisitExpr(Expr *E) {
20442  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20443  << E->getSourceRange();
20444  return ExprError();
20445  }
20446 
20447  /// Rebuild an expression which simply semantically wraps another
20448  /// expression which it shares the type and value kind of.
20449  template <class T> ExprResult rebuildSugarExpr(T *E) {
20450  ExprResult SubResult = Visit(E->getSubExpr());
20451  if (SubResult.isInvalid()) return ExprError();
20452 
20453  Expr *SubExpr = SubResult.get();
20454  E->setSubExpr(SubExpr);
20455  E->setType(SubExpr->getType());
20456  E->setValueKind(SubExpr->getValueKind());
20457  assert(E->getObjectKind() == OK_Ordinary);
20458  return E;
20459  }
20460 
20461  ExprResult VisitParenExpr(ParenExpr *E) {
20462  return rebuildSugarExpr(E);
20463  }
20464 
20465  ExprResult VisitUnaryExtension(UnaryOperator *E) {
20466  return rebuildSugarExpr(E);
20467  }
20468 
20469  ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20470  ExprResult SubResult = Visit(E->getSubExpr());
20471  if (SubResult.isInvalid()) return ExprError();
20472 
20473  Expr *SubExpr = SubResult.get();
20474  E->setSubExpr(SubExpr);
20475  E->setType(S.Context.getPointerType(SubExpr->getType()));
20476  assert(E->isPRValue());
20477  assert(E->getObjectKind() == OK_Ordinary);
20478  return E;
20479  }
20480 
20481  ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20482  if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20483 
20484  E->setType(VD->getType());
20485 
20486  assert(E->isPRValue());
20487  if (S.getLangOpts().CPlusPlus &&
20488  !(isa<CXXMethodDecl>(VD) &&
20489  cast<CXXMethodDecl>(VD)->isInstance()))
20490  E->setValueKind(VK_LValue);
20491 
20492  return E;
20493  }
20494 
20495  ExprResult VisitMemberExpr(MemberExpr *E) {
20496  return resolveDecl(E, E->getMemberDecl());
20497  }
20498 
20499  ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20500  return resolveDecl(E, E->getDecl());
20501  }
20502  };
20503 }
20504 
20505 /// Given a function expression of unknown-any type, try to rebuild it
20506 /// to have a function type.
20507 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
20508  ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20509  if (Result.isInvalid()) return ExprError();
20510  return S.DefaultFunctionArrayConversion(Result.get());
20511 }
20512 
20513 namespace {
20514  /// A visitor for rebuilding an expression of type __unknown_anytype
20515  /// into one which resolves the type directly on the referring
20516  /// expression. Strict preservation of the original source
20517  /// structure is not a goal.
20518  struct RebuildUnknownAnyExpr
20519  : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20520 
20521  Sema &S;
20522 
20523  /// The current destination type.
20524  QualType DestType;
20525 
20526  RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20527  : S(S), DestType(CastType) {}
20528 
20529  ExprResult VisitStmt(Stmt *S) {
20530  llvm_unreachable("unexpected statement!");
20531  }
20532 
20533  ExprResult VisitExpr(Expr *E) {
20534  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20535  << E->getSourceRange();
20536  return ExprError();
20537  }
20538 
20539  ExprResult VisitCallExpr(CallExpr *E);
20540  ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20541 
20542  /// Rebuild an expression which simply semantically wraps another
20543  /// expression which it shares the type and value kind of.
20544  template <class T> ExprResult rebuildSugarExpr(T *E) {
20545  ExprResult SubResult = Visit(E->getSubExpr());
20546  if (SubResult.isInvalid()) return ExprError();
20547  Expr *SubExpr = SubResult.get();
20548  E->setSubExpr(SubExpr);
20549  E->setType(SubExpr->getType());
20550  E->setValueKind(SubExpr->getValueKind());
20551  assert(E->getObjectKind() == OK_Ordinary);
20552  return E;
20553  }
20554 
20555  ExprResult VisitParenExpr(ParenExpr *E) {
20556  return rebuildSugarExpr(E);
20557  }
20558 
20559  ExprResult VisitUnaryExtension(UnaryOperator *E) {
20560  return rebuildSugarExpr(E);
20561  }
20562 
20563  ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20564  const PointerType *Ptr = DestType->getAs<PointerType>();
20565  if (!Ptr) {
20566  S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20567  << E->getSourceRange();
20568  return ExprError();
20569  }
20570 
20571  if (isa<CallExpr>(E->getSubExpr())) {
20572  S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20573  << E->getSourceRange();
20574  return ExprError();
20575  }
20576 
20577  assert(E->isPRValue());
20578  assert(E->getObjectKind() == OK_Ordinary);
20579  E->setType(DestType);
20580 
20581  // Build the sub-expression as if it were an object of the pointee type.
20582  DestType = Ptr->getPointeeType();
20583  ExprResult SubResult = Visit(E->getSubExpr());
20584  if (SubResult.isInvalid()) return ExprError();
20585  E->setSubExpr(SubResult.get());
20586  return E;
20587  }
20588 
20589  ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20590 
20591  ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20592 
20593  ExprResult VisitMemberExpr(MemberExpr *E) {
20594  return resolveDecl(E, E->getMemberDecl());
20595  }
20596 
20597  ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20598  return resolveDecl(E, E->getDecl());
20599  }
20600  };
20601 }
20602 
20603 /// Rebuilds a call expression which yielded __unknown_anytype.
20604 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20605  Expr *CalleeExpr = E->getCallee();
20606 
20607  enum FnKind {
20608  FK_MemberFunction,
20609  FK_FunctionPointer,
20610  FK_BlockPointer
20611  };
20612 
20613  FnKind Kind;
20614  QualType CalleeType = CalleeExpr->getType();
20615  if (CalleeType == S.Context.BoundMemberTy) {
20616  assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20617  Kind = FK_MemberFunction;
20618  CalleeType = Expr::findBoundMemberType(CalleeExpr);
20619  } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20620  CalleeType = Ptr->getPointeeType();
20621  Kind = FK_FunctionPointer;
20622  } else {
20623  CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20624  Kind = FK_BlockPointer;
20625  }
20626  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20627 
20628  // Verify that this is a legal result type of a function.
20629  if (DestType->isArrayType() || DestType->isFunctionType()) {
20630  unsigned diagID = diag::err_func_returning_array_function;
20631  if (Kind == FK_BlockPointer)
20632  diagID = diag::err_block_returning_array_function;
20633 
20634  S.Diag(E->getExprLoc(), diagID)
20635  << DestType->isFunctionType() << DestType;
20636  return ExprError();
20637  }
20638 
20639  // Otherwise, go ahead and set DestType as the call's result.
20640  E->setType(DestType.getNonLValueExprType(S.Context));
20642  assert(E->getObjectKind() == OK_Ordinary);
20643 
20644  // Rebuild the function type, replacing the result type with DestType.
20645  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20646  if (Proto) {
20647  // __unknown_anytype(...) is a special case used by the debugger when
20648  // it has no idea what a function's signature is.
20649  //
20650  // We want to build this call essentially under the K&R
20651  // unprototyped rules, but making a FunctionNoProtoType in C++
20652  // would foul up all sorts of assumptions. However, we cannot
20653  // simply pass all arguments as variadic arguments, nor can we
20654  // portably just call the function under a non-variadic type; see
20655  // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20656  // However, it turns out that in practice it is generally safe to
20657  // call a function declared as "A foo(B,C,D);" under the prototype
20658  // "A foo(B,C,D,...);". The only known exception is with the
20659  // Windows ABI, where any variadic function is implicitly cdecl
20660  // regardless of its normal CC. Therefore we change the parameter
20661  // types to match the types of the arguments.
20662  //
20663  // This is a hack, but it is far superior to moving the
20664  // corresponding target-specific code from IR-gen to Sema/AST.
20665 
20666  ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20667  SmallVector<QualType, 8> ArgTypes;
20668  if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20669  ArgTypes.reserve(E->getNumArgs());
20670  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20671  ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20672  }
20673  ParamTypes = ArgTypes;
20674  }
20675  DestType = S.Context.getFunctionType(DestType, ParamTypes,
20676  Proto->getExtProtoInfo());
20677  } else {
20678  DestType = S.Context.getFunctionNoProtoType(DestType,
20679  FnType->getExtInfo());
20680  }
20681 
20682  // Rebuild the appropriate pointer-to-function type.
20683  switch (Kind) {
20684  case FK_MemberFunction:
20685  // Nothing to do.
20686  break;
20687 
20688  case FK_FunctionPointer:
20689  DestType = S.Context.getPointerType(DestType);
20690  break;
20691 
20692  case FK_BlockPointer:
20693  DestType = S.Context.getBlockPointerType(DestType);
20694  break;
20695  }
20696 
20697  // Finally, we can recurse.
20698  ExprResult CalleeResult = Visit(CalleeExpr);
20699  if (!CalleeResult.isUsable()) return ExprError();
20700  E->setCallee(CalleeResult.get());
20701 
20702  // Bind a temporary if necessary.
20703  return S.MaybeBindToTemporary(E);
20704 }
20705 
20706 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20707  // Verify that this is a legal result type of a call.
20708  if (DestType->isArrayType() || DestType->isFunctionType()) {
20709  S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20710  << DestType->isFunctionType() << DestType;
20711  return ExprError();
20712  }
20713 
20714  // Rewrite the method result type if available.
20715  if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20716  assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20717  Method->setReturnType(DestType);
20718  }
20719 
20720  // Change the type of the message.
20721  E->setType(DestType.getNonReferenceType());
20723 
20724  return S.MaybeBindToTemporary(E);
20725 }
20726 
20727 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20728  // The only case we should ever see here is a function-to-pointer decay.
20729  if (E->getCastKind() == CK_FunctionToPointerDecay) {
20730  assert(E->isPRValue());
20731  assert(E->getObjectKind() == OK_Ordinary);
20732 
20733  E->setType(DestType);
20734 
20735  // Rebuild the sub-expression as the pointee (function) type.
20736  DestType = DestType->castAs<PointerType>()->getPointeeType();
20737 
20738  ExprResult Result = Visit(E->getSubExpr());
20739  if (!Result.isUsable()) return ExprError();
20740 
20741  E->setSubExpr(Result.get());
20742  return E;
20743  } else if (E->getCastKind() == CK_LValueToRValue) {
20744  assert(E->isPRValue());
20745  assert(E->getObjectKind() == OK_Ordinary);
20746 
20747  assert(isa<BlockPointerType>(E->getType()));
20748 
20749  E->setType(DestType);
20750 
20751  // The sub-expression has to be a lvalue reference, so rebuild it as such.
20752  DestType = S.Context.getLValueReferenceType(DestType);
20753 
20754  ExprResult Result = Visit(E->getSubExpr());
20755  if (!Result.isUsable()) return ExprError();
20756 
20757  E->setSubExpr(Result.get());
20758  return E;
20759  } else {
20760  llvm_unreachable("Unhandled cast type!");
20761  }
20762 }
20763 
20764 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20765  ExprValueKind ValueKind = VK_LValue;
20766  QualType Type = DestType;
20767 
20768  // We know how to make this work for certain kinds of decls:
20769 
20770  // - functions
20771  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20772  if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20773  DestType = Ptr->getPointeeType();
20774  ExprResult Result = resolveDecl(E, VD);
20775  if (Result.isInvalid()) return ExprError();
20776  return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20777  VK_PRValue);
20778  }
20779 
20780  if (!Type->isFunctionType()) {
20781  S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20782  << VD << E->getSourceRange();
20783  return ExprError();
20784  }
20785  if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20786  // We must match the FunctionDecl's type to the hack introduced in
20787  // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20788  // type. See the lengthy commentary in that routine.
20789  QualType FDT = FD->getType();
20790  const FunctionType *FnType = FDT->castAs<FunctionType>();
20791  const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20792  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20793  if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20794  SourceLocation Loc = FD->getLocation();
20796  S.Context, FD->getDeclContext(), Loc, Loc,
20797  FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20799  false /*isInlineSpecified*/, FD->hasPrototype(),
20800  /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20801 
20802  if (FD->getQualifier())
20803  NewFD->setQualifierInfo(FD->getQualifierLoc());
20804 
20806  for (const auto &AI : FT->param_types()) {
20807  ParmVarDecl *Param =
20808  S.BuildParmVarDeclForTypedef(FD, Loc, AI);
20809  Param->setScopeInfo(0, Params.size());
20810  Params.push_back(Param);
20811  }
20812  NewFD->setParams(Params);
20813  DRE->setDecl(NewFD);
20814  VD = DRE->getDecl();
20815  }
20816  }
20817 
20818  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20819  if (MD->isInstance()) {
20820  ValueKind = VK_PRValue;
20822  }
20823 
20824  // Function references aren't l-values in C.
20825  if (!S.getLangOpts().CPlusPlus)
20826  ValueKind = VK_PRValue;
20827 
20828  // - variables
20829  } else if (isa<VarDecl>(VD)) {
20830  if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20831  Type = RefTy->getPointeeType();
20832  } else if (Type->isFunctionType()) {
20833  S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20834  << VD << E->getSourceRange();
20835  return ExprError();
20836  }
20837 
20838  // - nothing else
20839  } else {
20840  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20841  << VD << E->getSourceRange();
20842  return ExprError();
20843  }
20844 
20845  // Modifying the declaration like this is friendly to IR-gen but
20846  // also really dangerous.
20847  VD->setType(DestType);
20848  E->setType(Type);
20849  E->setValueKind(ValueKind);
20850  return E;
20851 }
20852 
20853 /// Check a cast of an unknown-any type. We intentionally only
20854 /// trigger this for C-style casts.
20857  ExprValueKind &VK, CXXCastPath &Path) {
20858  // The type we're casting to must be either void or complete.
20859  if (!CastType->isVoidType() &&
20860  RequireCompleteType(TypeRange.getBegin(), CastType,
20861  diag::err_typecheck_cast_to_incomplete))
20862  return ExprError();
20863 
20864  // Rewrite the casted expression from scratch.
20865  ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20866  if (!result.isUsable()) return ExprError();
20867 
20868  CastExpr = result.get();
20869  VK = CastExpr->getValueKind();
20870  CastKind = CK_NoOp;
20871 
20872  return CastExpr;
20873 }
20874 
20876  return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20877 }
20878 
20880  Expr *arg, QualType &paramType) {
20881  // If the syntactic form of the argument is not an explicit cast of
20882  // any sort, just do default argument promotion.
20883  ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20884  if (!castArg) {
20886  if (result.isInvalid()) return ExprError();
20887  paramType = result.get()->getType();
20888  return result;
20889  }
20890 
20891  // Otherwise, use the type that was written in the explicit cast.
20892  assert(!arg->hasPlaceholderType());
20893  paramType = castArg->getTypeAsWritten();
20894 
20895  // Copy-initialize a parameter of that type.
20896  InitializedEntity entity =
20898  /*consumed*/ false);
20899  return PerformCopyInitialization(entity, callLoc, arg);
20900 }
20901 
20903  Expr *orig = E;
20904  unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20905  while (true) {
20906  E = E->IgnoreParenImpCasts();
20907  if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20908  E = call->getCallee();
20909  diagID = diag::err_uncasted_call_of_unknown_any;
20910  } else {
20911  break;
20912  }
20913  }
20914 
20915  SourceLocation loc;
20916  NamedDecl *d;
20917  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20918  loc = ref->getLocation();
20919  d = ref->getDecl();
20920  } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20921  loc = mem->getMemberLoc();
20922  d = mem->getMemberDecl();
20923  } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20924  diagID = diag::err_uncasted_call_of_unknown_any;
20925  loc = msg->getSelectorStartLoc();
20926  d = msg->getMethodDecl();
20927  if (!d) {
20928  S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20929  << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20930  << orig->getSourceRange();
20931  return ExprError();
20932  }
20933  } else {
20934  S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20935  << E->getSourceRange();
20936  return ExprError();
20937  }
20938 
20939  S.Diag(loc, diagID) << d << orig->getSourceRange();
20940 
20941  // Never recoverable.
20942  return ExprError();
20943 }
20944 
20945 /// Check for operands with placeholder types and complain if found.
20946 /// Returns ExprError() if there was an error and no recovery was possible.
20948  if (!Context.isDependenceAllowed()) {
20949  // C cannot handle TypoExpr nodes on either side of a binop because it
20950  // doesn't handle dependent types properly, so make sure any TypoExprs have
20951  // been dealt with before checking the operands.
20953  if (!Result.isUsable()) return ExprError();
20954  E = Result.get();
20955  }
20956 
20957  const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20958  if (!placeholderType) return E;
20959 
20960  switch (placeholderType->getKind()) {
20961 
20962  // Overloaded expressions.
20963  case BuiltinType::Overload: {
20964  // Try to resolve a single function template specialization.
20965  // This is obligatory.
20966  ExprResult Result = E;
20968  return Result;
20969 
20970  // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20971  // leaves Result unchanged on failure.
20972  Result = E;
20974  return Result;
20975 
20976  // If that failed, try to recover with a call.
20977  tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20978  /*complain*/ true);
20979  return Result;
20980  }
20981 
20982  // Bound member functions.
20983  case BuiltinType::BoundMember: {
20984  ExprResult result = E;
20985  const Expr *BME = E->IgnoreParens();
20986  PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20987  // Try to give a nicer diagnostic if it is a bound member that we recognize.
20988  if (isa<CXXPseudoDestructorExpr>(BME)) {
20989  PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20990  } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20991  if (ME->getMemberNameInfo().getName().getNameKind() ==
20993  PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20994  }
20995  tryToRecoverWithCall(result, PD,
20996  /*complain*/ true);
20997  return result;
20998  }
20999 
21000  // ARC unbridged casts.
21001  case BuiltinType::ARCUnbridgedCast: {
21002  Expr *realCast = stripARCUnbridgedCast(E);
21003  diagnoseARCUnbridgedCast(realCast);
21004  return realCast;
21005  }
21006 
21007  // Expressions of unknown type.
21008  case BuiltinType::UnknownAny:
21009  return diagnoseUnknownAnyExpr(*this, E);
21010 
21011  // Pseudo-objects.
21012  case BuiltinType::PseudoObject:
21013  return checkPseudoObjectRValue(E);
21014 
21015  case BuiltinType::BuiltinFn: {
21016  // Accept __noop without parens by implicitly converting it to a call expr.
21017  auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21018  if (DRE) {
21019  auto *FD = cast<FunctionDecl>(DRE->getDecl());
21020  unsigned BuiltinID = FD->getBuiltinID();
21021  if (BuiltinID == Builtin::BI__noop) {
21022  E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21023  CK_BuiltinFnToFnPtr)
21024  .get();
21025  return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21027  FPOptionsOverride());
21028  }
21029 
21030  if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21031  // Any use of these other than a direct call is ill-formed as of C++20,
21032  // because they are not addressable functions. In earlier language
21033  // modes, warn and force an instantiation of the real body.
21034  Diag(E->getBeginLoc(),
21036  ? diag::err_use_of_unaddressable_function
21037  : diag::warn_cxx20_compat_use_of_unaddressable_function);
21038  if (FD->isImplicitlyInstantiable()) {
21039  // Require a definition here because a normal attempt at
21040  // instantiation for a builtin will be ignored, and we won't try
21041  // again later. We assume that the definition of the template
21042  // precedes this use.
21044  /*Recursive=*/false,
21045  /*DefinitionRequired=*/true,
21046  /*AtEndOfTU=*/false);
21047  }
21048  // Produce a properly-typed reference to the function.
21049  CXXScopeSpec SS;
21050  SS.Adopt(DRE->getQualifierLoc());
21051  TemplateArgumentListInfo TemplateArgs;
21052  DRE->copyTemplateArgumentsInto(TemplateArgs);
21053  return BuildDeclRefExpr(
21054  FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21055  DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21056  DRE->getTemplateKeywordLoc(),
21057  DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21058  }
21059  }
21060 
21061  Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21062  return ExprError();
21063  }
21064 
21065  case BuiltinType::IncompleteMatrixIdx:
21066  Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21067  ->getRowIdx()
21068  ->getBeginLoc(),
21069  diag::err_matrix_incomplete_index);
21070  return ExprError();
21071 
21072  // Expressions of unknown type.
21073  case BuiltinType::OMPArraySection:
21074  Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
21075  return ExprError();
21076 
21077  // Expressions of unknown type.
21078  case BuiltinType::OMPArrayShaping:
21079  return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21080 
21081  case BuiltinType::OMPIterator:
21082  return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21083 
21084  // Everything else should be impossible.
21085 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21086  case BuiltinType::Id:
21087 #include "clang/Basic/OpenCLImageTypes.def"
21088 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21089  case BuiltinType::Id:
21090 #include "clang/Basic/OpenCLExtensionTypes.def"
21091 #define SVE_TYPE(Name, Id, SingletonId) \
21092  case BuiltinType::Id:
21093 #include "clang/Basic/AArch64SVEACLETypes.def"
21094 #define PPC_VECTOR_TYPE(Name, Id, Size) \
21095  case BuiltinType::Id:
21096 #include "clang/Basic/PPCTypes.def"
21097 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21098 #include "clang/Basic/RISCVVTypes.def"
21099 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21100 #define PLACEHOLDER_TYPE(Id, SingletonId)
21101 #include "clang/AST/BuiltinTypes.def"
21102  break;
21103  }
21104 
21105  llvm_unreachable("invalid placeholder type!");
21106 }
21107 
21109  if (E->isTypeDependent())
21110  return true;
21112  return E->getType()->isIntegralOrEnumerationType();
21113  return false;
21114 }
21115 
21116 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21117 ExprResult
21119  assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
21120  "Unknown Objective-C Boolean value!");
21122  if (!Context.getBOOLDecl()) {
21123  LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
21125  if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
21126  NamedDecl *ND = Result.getFoundDecl();
21127  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
21128  Context.setBOOLDecl(TD);
21129  }
21130  }
21131  if (Context.getBOOLDecl())
21132  BoolT = Context.getBOOLType();
21133  return new (Context)
21134  ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
21135 }
21136 
21139  SourceLocation RParen) {
21140  auto FindSpecVersion =
21141  [&](StringRef Platform) -> std::optional<VersionTuple> {
21142  auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21143  return Spec.getPlatform() == Platform;
21144  });
21145  // Transcribe the "ios" availability check to "maccatalyst" when compiling
21146  // for "maccatalyst" if "maccatalyst" is not specified.
21147  if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
21148  Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21149  return Spec.getPlatform() == "ios";
21150  });
21151  }
21152  if (Spec == AvailSpecs.end())
21153  return std::nullopt;
21154  return Spec->getVersion();
21155  };
21156 
21157  VersionTuple Version;
21158  if (auto MaybeVersion =
21159  FindSpecVersion(Context.getTargetInfo().getPlatformName()))
21160  Version = *MaybeVersion;
21161 
21162  // The use of `@available` in the enclosing context should be analyzed to
21163  // warn when it's used inappropriately (i.e. not if(@available)).
21165  Context->HasPotentialAvailabilityViolations = true;
21166 
21167  return new (Context)
21168  ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
21169 }
21170 
21172  ArrayRef<Expr *> SubExprs, QualType T) {
21173  if (!Context.getLangOpts().RecoveryAST)
21174  return ExprError();
21175 
21176  if (isSFINAEContext())
21177  return ExprError();
21178 
21179  if (T.isNull() || T->isUndeducedType() ||
21180  !Context.getLangOpts().RecoveryASTType)
21181  // We don't know the concrete type, fallback to dependent type.
21182  T = Context.DependentTy;
21183 
21184  return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21185 }
clang::OpenCL
@ OpenCL
Definition: LangStandard.h:62
clang::Type::isIntegralType
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1954
clang::StmtVisitor
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:183
ImmediateCallVisitor::shouldVisitImplicitCode
bool shouldVisitImplicitCode() const
Definition: SemaExpr.cpp:5926
clang::OMPIteratorHelperData::Update
Expr * Update
Update expression for the originally specified iteration variable, calculated as VD = Begin + Counter...
Definition: ExprOpenMP.h:243
checkForArray
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:12264
clang::BuiltinType
This class is used for builtin types like 'int'.
Definition: Type.h:2627
clang::ASTContext::areCommonBaseCompatible
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
Definition: ASTContext.cpp:10006
clang::Expr::EvaluateKnownConstIntCheckOverflow
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Definition: ExprConstant.cpp:15488
captureVariablyModifiedType
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4485
clang::Sema::CheckConversionToObjCLiteral
bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExpr.cpp:17059
clang::NestedNameSpecifier::Create
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
Definition: NestedNameSpecifier.cpp:59
ConstFunction
@ ConstFunction
Definition: SemaExpr.cpp:13738
clang::Sema::CheckVectorLogicalOperands
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13389
clang::DeclarationNameInfo::setCXXLiteralOperatorNameLoc
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
Definition: DeclarationName.h:850
clang::Sema::CheckShadow
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8180
clang::InternalLinkage
@ InternalLinkage
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:31
clang::Type::STK_FixedPoint
@ STK_FixedPoint
Definition: Type.h:2293
clang::Sema::hasAnyUnrecoverableErrorsInThisFunction
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2279
clang::interp::APFloat
llvm::APFloat APFloat
Definition: Floating.h:23
OpenCLArithmeticConversions
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:8649
clang::Token::startToken
void startToken()
Reset all flags to cleared.
Definition: Token.h:171
clang::TagDecl::hasNameForLinkage
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3660
clang::TypoCorrection::getCorrectionRange
SourceRange getCorrectionRange() const
Definition: TypoCorrection.h:226
clang::Language::CUDA
@ CUDA
clang::UnqualifiedId
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:973
clang::ObjCInterfaceDecl
Represents an ObjC class declaration.
Definition: DeclObjC.h:1146
clang::Sema::DiagnoseEqualityWithExtraParens
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:20332
clang::NonOdrUseReason
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition: Specifiers.h:161
clang::Sema::SemaConvertVectorExpr
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
SemaConvertVectorExpr - Handle __builtin_convertvector.
Definition: SemaChecking.cpp:7738
clang::ASTContext::getTypeSizeInChars
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Definition: ASTContext.cpp:2560
clang::Sema::RequireCompleteSizedExprType
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &... Args)
Definition: Sema.h:2531
clang::sema::Capture::isThisCapture
bool isThisCapture() const
Definition: ScopeInfo.h:620
NonConstCaptureKind
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:13691
clang::isTargetAddressSpace
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:74
clang::Sema::BuildDeclarationNameExpr
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3225
clang::ASTContext::LongDoubleTy
CanQualType LongDoubleTy
Definition: ASTContext.h:1090
clang::Sema::BuildCXXDefaultInitExpr
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:6042
clang::QualType::isCForbiddenLValueType
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition: Type.h:6851
clang::Sema::CurContext
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:421
checkSizelessVectorShift
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:11865
clang::MatrixSubscriptExpr
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition: Expr.h:2735
ExprLooksBoolean
static bool ExprLooksBoolean(Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:9247
clang::Expr::getValueKind
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:432
clang::Type::isSamplerT
bool isSamplerT() const
Definition: Type.h:7089
isOverflowingIntegerType
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:15775
clang::Sema::RefsMinusAssignments
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:1626
clang::Sema::isSFINAEContext
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
Definition: SemaTemplateInstantiate.cpp:1015
clang::ASTContext::getQualifiedType
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2111
diagnosePointerIncompatibility
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:11398
clang::DeclRefExpr::getFoundDecl
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition: Expr.h:1344
clang::Sema::DefaultArgumentPromotion
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:857
clang::CompoundStmt::getStmtExprResult
Stmt * getStmtExprResult()
Definition: Stmt.h:1535
clang::LookupResult::setNamingClass
void setNamingClass(CXXRecordDecl *Record)
Sets the 'naming class' for this lookup.
Definition: Lookup.h:434
Builtins.h
getDeclFromExpr
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:15008
clang::Expr::MLV_IncompleteType
@ MLV_IncompleteType
Definition: Expr.h:299
clang::Sema::CheckAdditionOperands
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11408
clang::PredefinedExpr::PrettyFunction
@ PrettyFunction
Definition: Expr.h:1989
clang::Type::isRecordType
bool isRecordType() const
Definition: Type.h:6986
clang::QualType::DK_nontrivial_c_struct
@ DK_nontrivial_c_struct
Definition: Type.h:1281
clang::FunctionTypeLoc::getNumParams
unsigned getNumParams() const
Definition: TypeLoc.h:1458
clang::LangAS::opencl_private
@ opencl_private
clang::Sema::getCapturedDeclRefType
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
Definition: SemaExpr.cpp:19300
EmitDiagnosticForLogicalAndInLogicalOr
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
Definition: SemaExpr.cpp:15434
clang::ASTContext::areLaxCompatibleSveTypes
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition: ASTContext.cpp:9536
clang::sema::Capture::markUsed
void markUsed(bool IsODRUse)
Definition: ScopeInfo.h:639
clang::MangleNumberingContext::getManglingNumber
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
convertPointersToCompositeType
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Returns false if the pointers are converted to a composite type, true otherwise.
Definition: SemaExpr.cpp:12032
max
__DEVICE__ int max(int __a, int __b)
Definition: __clang_cuda_math.h:196
clang::sema::Capture::getLocation
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:657
clang::LangOptions::isSignedOverflowDefined
bool isSignedOverflowDefined() const
Definition: LangOptions.h:533
clang::isLambdaCallOperator
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
clang::ASTContext::getIntegerTypeOrder
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
Definition: ASTContext.cpp:7300
clang::Sema::isOpenMPGlobalCapturedDecl
bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified global variable must be captured by outer capture regions.
Definition: SemaOpenMP.cpp:2651
clang::FunctionDecl::isDefaulted
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2282
clang::Type::getAsArrayTypeUnsafe
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:7463
clang::QualType::getObjCLifetime
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1194
clang::BlockDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:4418
clang::ImaginaryLiteral
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1730
clang::Type::isRealType
bool isRealType() const
Definition: Type.cpp:2167
clang::Expr::setValueKind
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:449
clang::isGenericLambdaCallOperatorSpecialization
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:38
clang::ASTContext::IncompleteMatrixIdxTy
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1116
CheckIndirectionOperand
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
Definition: SemaExpr.cpp:14766
clang::ConstantExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1100
clang::Sema::ScalarTypeToBooleanCastKind
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:703
clang::StringLiteral::getCodeUnit
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1877
clang::Sema::runWithSufficientStackSpace
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:503
clang::Sema::CheckSizelessVectorCompareOperands
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13226
clang::CXXConstructorDecl
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2448
clang::Sema::CheckPlaceholderExpr
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20947
clang::ASTContext::getTypeDeclType
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1554
clang::Sema::CheckLValueToRValueConversionOperand
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:19661
OEK_Member
@ OEK_Member
Definition: SemaExpr.cpp:13871
clang::Sema::GetSignedVectorType
QualType GetSignedVectorType(QualType V)
Definition: SemaExpr.cpp:13106
clang::Type::isConstantMatrixType
bool isConstantMatrixType() const
Definition: Type.h:7016
clang::QualType::hasNonTrivialToPrimitiveCopyCUnion
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition: Type.h:6790
clang::CC_X86FastCall
@ CC_X86FastCall
Definition: Specifiers.h:269
clang::ASTContext::getBOOLType
QualType getBOOLType() const
type of 'BOOL' type.
Definition: ASTContext.h:2059
clang::CXXConversionDecl::isLambdaToBlockPointerConversion
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:2835
clang::Expr::LValueClassification
LValueClassification
Definition: Expr.h:277
clang::StringLiteral::UTF16
@ UTF16
Definition: Expr.h:1801
clang::CharacterLiteral::CharacterKind
CharacterKind
Definition: Expr.h:1598
clang::ICK_Lvalue_To_Rvalue
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
clang::Type::hasAttr
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition: Type.cpp:1800
clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:1330
clang::Type::isBlockPointerType
bool isBlockPointerType() const
Definition: Type.h:6904
clang::ASTContext::hasDirectOwnershipQualifier
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
Definition: ASTContext.cpp:9588
clang::Sema::IncompatiblePointer
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:12375
clang::AsTypeExpr
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition: Expr.h:5876
Specifiers.h
clang::FunctionProtoType::getExceptionSpecType
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4259
clang::CXXRecordDecl::hasAnyDependentBases
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:566
clang::Sema::DiagnoseUseOfDecl
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:222
clang::FPOptions::isFPConstrained
bool isFPConstrained() const
Definition: LangOptions.h:736
clang::QualType::getLocalQualifiers
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:6667
clang::Sema::ActOnInitList
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7573
clang::interp::APInt
llvm::APInt APInt
Definition: Integral.h:29
clang::Sema::CleanupVarDeclMarking
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19697
clang::CleanupInfo::setExprNeedsCleanups
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
clang::Sema::isExternalWithNoLinkageType
bool isExternalWithNoLinkageType(ValueDecl *VD)
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can't b...
Definition: Sema.cpp:789
clang::Sema::ConditionKind::Boolean
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
clang::BinaryOperator::isCompoundAssignmentOp
bool isCompoundAssignmentOp() const
Definition: Expr.h:3958
clang::Sema::ForVisibleRedeclaration
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:4344
clang::ObjCObjectPointerType::getInterfaceType
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1700
clang::DeclRefExpr::getLocation
SourceLocation getLocation() const
Definition: Expr.h:1315
TreeTransform.h
clang::VarDecl::setTemplateSpecializationKind
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2795
clang::OK_Ordinary
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:139
clang::Sema::deduceClosureReturnType
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:705
clang::OffsetOfExpr::Create
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition: Expr.cpp:1639
clang::Sema::PreferredConditionType
QualType PreferredConditionType(ConditionKind K) const
Definition: Sema.h:12830
clang::ASTContext::getCharWidth
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2278
clang::TypeSourceInfo::getType
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:6617
clang::Sema::CheckVectorCompareOperands
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
Definition: SemaExpr.cpp:13165
diagnoseDistinctPointerComparison
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:12021
clang::Sema::LookupLiteralOperator
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit=nullptr)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal,...
Definition: SemaLookup.cpp:3645
clang::Sema::CFT_Host
@ CFT_Host
Definition: Sema.h:13051
clang::LookupResult::setLookupName
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:248
clang::Sema::CUDAFunctionTarget
CUDAFunctionTarget
Definition: Sema.h:13048
clang::Sema::BuildDeclRefExpr
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2001
clang::QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition: Type.h:6778
clang::TargetInfo::supportsExtendIntArgs
virtual bool supportsExtendIntArgs() const
Whether the option -fextend-arguments={32,64} is supported on the target.
Definition: TargetInfo.h:1544
clang::Expr::EvalStatus::HasSideEffects
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:597
clang::Sema::IncompatibleBlockPointer
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:12425
clang::UnresolvedSetImpl
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
clang::FunctionDecl::getReturnType
QualType getReturnType() const
Definition: Decl.h:2638
clang::CXXScopeSpec::Adopt
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
clang::LangOptions::getOpenCLCompatibleVersion
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
clang::VectorType::SveFixedLengthPredicateVector
@ SveFixedLengthPredicateVector
is AArch64 SVE fixed-length predicate vector
Definition: Type.h:3390
clang::ASTContext::getBitIntType
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
Definition: ASTContext.cpp:4648
clang::SourceLocExpr::IdentKind
IdentKind
Definition: Expr.h:4695
clang::Expr::isOrdinaryOrBitFieldObject
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:443
clang::DeclarationName::CXXLiteralOperatorName
@ CXXLiteralOperatorName
Definition: DeclarationName.h:219
clang::Sema::CheckStaticArrayArgument
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
Definition: SemaExpr.cpp:6488
clang::DeclaratorDecl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:819
clang::ParmVarDecl::getOriginalType
QualType getOriginalType() const
Definition: Decl.cpp:2843
captureInBlock
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
Definition: SemaExpr.cpp:18721
checkArithmeticBinOpPointerOperands
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
Definition: SemaExpr.cpp:11264
clang::UsedDeclVisitor
Definition: UsedDeclVisitor.h:21
clang::Sema::TypeDiagnoser
Abstract class used to diagnose incomplete types.
Definition: Sema.h:2172
clang::Qualifiers::withoutObjCGCAttr
Qualifiers withoutObjCGCAttr() const
Definition: Type.h:334
clang::Sema::ActOnParenListExpr
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:8342
clang::Expr::isLValue
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:272
clang::Expr::MLV_DuplicateVectorComponents
@ MLV_DuplicateVectorComponents
Definition: Expr.h:296
DiagnoseLogicalAndInLogicalOrRHS
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
Definition: SemaExpr.cpp:15467
rebuildUnknownAnyFunction
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type.
Definition: SemaExpr.cpp:20507
clang::Sema::FunctionVoidPointer
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:12371
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:210
clang::TargetInfo::getBuiltinVaListKind
virtual BuiltinVaListKind getBuiltinVaListKind() const =0
Returns the kind of __builtin_va_list type that should be used with this target.
clang::Sema::stripARCUnbridgedCast
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
Definition: SemaExprObjC.cpp:4539
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:23
clang::ObjCMethodFamily
ObjCMethodFamily
A family of Objective-C methods.
Definition: IdentifierTable.h:697
clang::Type::isSignedFixedPointType
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7273
clang::Sema::ActOnGNUNullExpr
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16934
clang::Sema::AllowFoldKind
AllowFoldKind
Definition: Sema.h:12906
clang::LookupResult::end
iterator end() const
Definition: Lookup.h:336
clang::DeclContext
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1389
clang::Sema::CheckExtVectorCast
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
Definition: SemaExpr.cpp:8132
clang::Type::isVoidPointerType
bool isVoidPointerType() const
Definition: Type.cpp:593
clang::Sema::ConvertMemberDefaultInitExpression
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
Definition: SemaDeclCXX.cpp:4060
clang::VarDecl::mightBeUsableInConstantExpressions
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2392
clang::CXXConversionDecl
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2778
checkEnumArithmeticConversions
static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc, Sema::ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
Definition: SemaExpr.cpp:1470
clang::Decl::hasAttr
bool hasAttr() const
Definition: DeclBase.h:560
clang::VarDecl::hasGlobalStorage
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1185
clang::LookupResult::isSingleResult
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:308
clang::TypoCorrection
Simple class containing the result of Sema::CorrectTypo.
Definition: TypoCorrection.h:42
Data
const char * Data
Definition: StandardLibrary.cpp:35
clang::DeclRefExpr::getQualifier
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1334
clang::FixItHint::CreateInsertion
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
clang::Sema::DiagnoseSentinelCalls
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:406
clang::Sema::isOpenMPTargetCapturedDecl
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified variable is captured by 'target' directive.
Definition: SemaOpenMP.cpp:2637
clang::ParenExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2143
clang::Sema::MarkMemberReferenced
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:20001
clang::Sema::CheckFloatComparison
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
Definition: SemaChecking.cpp:12191
clang::TypoCorrection::getCorrectionSpecifier
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Definition: TypoCorrection.h:91
clang::BinaryOperator::isComparisonOp
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3914
clang::ICK_Identity
@ ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:106
clang::Sema::LookupInstanceMethodInGlobalPool
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition: Sema.h:4951
clang::Sema::getASTContext
ASTContext & getASTContext() const
Definition: Sema.h:1662
clang::BinaryOperator::isAdditiveOp
bool isAdditiveOp() const
Definition: Expr.h:3901
clang::VarDecl::getCanonicalDecl
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2186
clang::Sema::isOpenMPCapturedDecl
VarDecl * isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo=false, unsigned StopAt=0)
Check if the specified variable is used in one of the private clauses (private, firstprivate,...
Definition: SemaOpenMP.cpp:2327
clang::Sema::NTCUC_Assignment
@ NTCUC_Assignment
Definition: Sema.h:3003
clang::OverloadCandidateSet::CSK_Normal
@ CSK_Normal
Normal lookup.
Definition: Overload.h:955
clang::SourceLocExpr::Column
@ Column
Definition: Expr.h:4695
ImmediateCallVisitor::VisitCXXDefaultInitExpr
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E)
Definition: SemaExpr.cpp:5963
clang::QualType::isConstQualified
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6707
clang::Sema::getCurFunction
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1987
clang::Sema::InstantiateVariableDefinition
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
Definition: SemaTemplateInstantiateDecl.cpp:5406
clang::ConstantArrayType
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3065
clang::LangOptions::AltivecSrcCompatKind::GCC
@ GCC
clang::Sema::CheckAddressOfOperand
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14529
clang::Type::STK_IntegralComplex
@ STK_IntegralComplex
Definition: Type.h:2291
clang::Sema::SourceMgr
SourceManager & SourceMgr
Definition: Sema.h:412
clang::FunctionDecl::isConstexpr
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2367
Used
@ Used
Definition: ObjCUnusedIVarsChecker.cpp:29
clang::Sema::NTCUC_LValueToRValueVolatile
@ NTCUC_LValueToRValueVolatile
Definition: Sema.h:3009
Diag
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Definition: LiteralSupport.cpp:79
isReferenceToNonConstCapture
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:13692
clang::SourceManager::isInMainFile
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
Definition: SourceManager.cpp:1597
clang::FunctionDecl::isDeleted
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2422
clang::Sema::checkNonTrivialCUnionInInitializer
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
Definition: SemaDecl.cpp:12728
clang::TargetInfo::getLongWidth
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:482
clang::Sema::checkDeclIsAllowedInOpenMPTarget
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
Definition: SemaOpenMP.cpp:23007
clang::UnaryOperator::Create
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4679
clang::NamedDecl::isExternallyVisible
bool isExternallyVisible() const
Definition: Decl.h:407
clang::Qualifiers::OCL_Weak
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:177
clang::OMPIteratorHelperData
Helper expressions and declaration for OMPIteratorExpr class for each iteration space.
Definition: ExprOpenMP.h:235
SemaInternal.h
clang::Sema::VariadicMethod
@ VariadicMethod
Definition: Sema.h:12274
clang::Sema::ExpressionEvaluationContext::UnevaluatedAbstract
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
clang::Sema::ActOnIdExpression
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2485
clang::ConstantArrayType::getSize
const llvm::APInt & getSize() const
Definition: Type.h:3088
clang::Sema::ConvertArgumentsForCall
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
Definition: SemaExpr.cpp:6249
clang::Sema::NoteDeletedFunction
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:115
clang::BindingDecl
A binding in a decomposition declaration.
Definition: DeclCXX.h:4020
clang::PredefinedExpr::FuncDName
@ FuncDName
Definition: Expr.h:1986
clang::Sema::CallExprUnaryConversions
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:752
clang::Expr::IgnoreImplicit
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3024
clang::ASTContext::VoidTy
CanQualType VoidTy
Definition: ASTContext.h:1078
clang::sema::LambdaScopeInfo::Mutable
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:853
clang::Type::isCharType
bool isCharType() const
Definition: Type.cpp:1985
clang::Sema::LOLR_StringTemplatePack
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition: Sema.h:4381
llvm::SmallVector
Definition: LLVM.h:35
clang::APValue::getInt
APSInt & getInt()
Definition: APValue.h:415
Lookup.h
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:597
clang::PredefinedExpr::LFuncSig
@ LFuncSig
Definition: Expr.h:1988
clang::if
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
Definition: RecursiveASTVisitor.h:1081
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::Sema::FunctionScopes
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:805
clang::Sema::InvalidLogicalVectorOperands
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Definition: SemaExpr.cpp:10376
clang::Sema::ActOnBinOp
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15574
handleIntegerConversion
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1288
clang::Qualifiers::removeAddressSpace
void removeAddressSpace()
Definition: Type.h:402
clang::QualType::getQualifiers
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6675
clang::Expr::MLV_ConstQualified
@ MLV_ConstQualified
Definition: Expr.h:300
clang::TargetCXXABI::isMicrosoft
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:138
handleFloatConversion
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
Definition: SemaExpr.cpp:1195
clang::ASTContext::getIntWidth
unsigned getIntWidth(QualType T) const
Definition: ASTContext.cpp:10982
clang::ActionResult::getAs
T * getAs()
Definition: Ownership.h:170
clang::DiagnosticsEngine::isIgnored
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:911
clang::CXXDefaultInitExpr::getExpr
Expr * getExpr()
Get the initialization expression that will be used.
Definition: ExprCXX.cpp:1026
diagnoseObjCLiteralComparison
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:12172
clang::Sema::AnalysisWarnings
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:9808
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:134
clang::Sema::LookupOverloadedOperatorName
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
Definition: SemaLookup.cpp:3307
ConstUnknown
@ ConstUnknown
Definition: SemaExpr.cpp:13743
clang::Type::STK_FloatingComplex
@ STK_FloatingComplex
Definition: Type.h:2292
clang::NamedDecl
This represents a decl that may have a name.
Definition: Decl.h:247
clang::Qualifiers::withoutObjCLifetime
Qualifiers withoutObjCLifetime() const
Definition: Type.h:339
clang::ASTContext::OMPArraySectionTy
CanQualType OMPArraySectionTy
Definition: ASTContext.h:1117
clang::ASTContext::BuiltinInfo
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:633
clang::ParenListExpr
Definition: Expr.h:5384
clang::ObjCInterfaceDecl::ivar_begin
ivar_iterator ivar_begin() const
Definition: DeclObjC.h:1441
clang::Sema::UseArgumentDependentLookup
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3135
clang::CharacterLiteral::getValue
unsigned getValue() const
Definition: Expr.h:1630
clang::SourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:219
clang::Sema::TemporaryMaterializationConversion
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:8255
clang::Sema::PrepareScalarCast
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
Definition: SemaExpr.cpp:7697
clang::Expr::MLV_MemberFunction
@ MLV_MemberFunction
Definition: Expr.h:305
clang::Sema::DiagnoseSelfMove
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
Definition: SemaChecking.cpp:17143
clang::Sema::CheckMultiplyDivideOperands
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:11051
clang::ASTContext::CUDADeviceVarODRUsedByHost
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1143
clang::TreeTransform
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Definition: TreeTransform.h:102
clang::OR_Success
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
EvaluatedExprVisitor.h
clang::MemberExpr::Create
static MemberExpr * Create(const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR)
Definition: Expr.cpp:1714
clang::FunctionType::ExtInfo::withNoReturn
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3867
TargetInfo.h
clang::NamedDecl::getUnderlyingDecl
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:459
clang::NOUR_Discarded
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition: Specifiers.h:171
clang::Sema::findMacroSpelling
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:2070
clang::MultiVersionKind::Target
@ Target
handleComplexIntConversion
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
Definition: SemaExpr.cpp:1338
clang::LookupResult::clear
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:580
clang::BlockDecl::setSignatureAsWritten
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition: Decl.h:4414
clang::QualType::getNonReferenceType
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6844
clang::CastExpr::getSubExpr
Expr * getSubExpr()
Definition: Expr.h:3533
CXXInheritance.h
clang::sema::LambdaScopeInfo::NumExplicitCaptures
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:850
emitEmptyLookupTypoDiagnostic
static void emitEmptyLookupTypoDiagnostic(const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, DeclarationName Typo, SourceLocation TypoLoc, ArrayRef< Expr * > Args, unsigned DiagnosticID, unsigned DiagnosticSuggestID)
Definition: SemaExpr.cpp:2168
clang::Sema::IsStringLiteralToNonConstPointerConversion
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
Definition: SemaExprCXX.cpp:4060
clang::ASTContext::PseudoObjectTy
CanQualType PseudoObjectTy
Definition: ASTContext.h:1108
clang::Sema::DefineInheritingConstructor
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
Definition: SemaDeclCXX.cpp:13722
clang::FixedPointLiteral::CreateFromRawInt
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:1005
clang::Sema::ExpressionEvaluationContextRecord::isUnevaluated
bool isUnevaluated() const
Definition: Sema.h:1368
clang::ASTContext::DeclarationNames
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:635
clang::Sema::FindCompositeObjCPointerType
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
Definition: SemaExpr.cpp:9029
clang::Sema::isCheckingDefaultArgumentOrInitializer
bool isCheckingDefaultArgumentOrInitializer() const
Definition: Sema.h:9688
clang::Sema::ResolveSingleFunctionTemplateSpecialization
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
Definition: SemaOverload.cpp:12760
clang::ASTContext::getObjCSelRedefinitionType
QualType getObjCSelRedefinitionType() const
Retrieve the type that 'SEL' has been defined to, which may be different from the built-in 'SEL' if '...
Definition: ASTContext.h:1845
clang::TypeLocBuilder::getTypeSourceInfo
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Definition: TypeLocBuilder.h:107
clang::Stmt::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:325
clang::Sema::GatherArgumentsForCall
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:6366
BuildOverloadedBinOp
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHS, Expr *RHS)
Build an overloaded binary operator expression in the given scope.
Definition: SemaExpr.cpp:15601
clang::TSK_Undeclared
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:179
clang::UnresolvedMemberExpr
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3883
clang::FunctionDecl::getCanonicalDecl
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3398
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:736
clang::TypeDecl::getTypeForDecl
const Type * getTypeForDecl() const
Definition: Decl.h:3270
clang::NonTypeTemplateParmDecl
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Definition: DeclTemplate.h:1407
clang::Expr::getObjectKind
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:439
clang::Type::isScalarType
bool isScalarType() const
Definition: Type.h:7291
clang::Selector::isUnarySelector
bool isUnarySelector() const
Definition: IdentifierTable.h:836
clang::Type::isMatrixType
bool isMatrixType() const
Definition: Type.h:7012
clang::FunctionDecl::getParamDecl
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2607
clang::Sema::ActOnAsTypeExpr
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_astype(...)
Definition: SemaExpr.cpp:7113
clang::Declarator::getIdentifier
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2251
clang::DeclarationNameInfo::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclarationName.h:876
clang::Sema::LOLR_ErrorNoDiagnostic
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition: Sema.h:4367
clang::NestedNameSpecifier
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
Definition: NestedNameSpecifier.h:50
clang::DynamicInitKind::Initializer
@ Initializer
IsArithmeticOp
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:9186
clang::ObjCIvarDecl::getAccessControl
AccessControl getAccessControl() const
Definition: DeclObjC.h:1988
tryGCCVectorConvertAndSplat
static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, ExprResult *Vector)
Attempt to convert and splat Scalar into a vector whose types matches Vector following GCC conversion...
Definition: SemaExpr.cpp:10562
clang::Expr::LV_ClassTemporary
@ LV_ClassTemporary
Definition: Expr.h:286
clang::Sema::BuildStmtExpr
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
Definition: SemaExpr.cpp:16139
clang::Type::ScalarTypeKind
ScalarTypeKind
Definition: Type.h:2283
clang::OMF_finalize
@ OMF_finalize
Definition: IdentifierTable.h:715
clang::OMF_init
@ OMF_init
Definition: IdentifierTable.h:707
clang::TypoCorrection::isOverloaded
bool isOverloaded() const
Definition: TypoCorrection.h:215
clang::TypoCorrection::getCorrectionDeclAs
DeclClass * getCorrectionDeclAs() const
Definition: TypoCorrection.h:156
isScopedEnumerationType
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:11663
LookupStdSourceLocationImpl
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16952
clang::ASTContext::getFloatTypeSemantics
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
Definition: ASTContext.cpp:1750
clang::ObjCObjectPointerType::isObjCQualifiedIdType
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:6358
clang::QualType::getCanonicalType
QualType getCanonicalType() const
Definition: Type.h:6687
clang::FieldDecl
Represents a member of a struct/union/class.
Definition: Decl.h:2943
clang::VectorType::NeonVector
@ NeonVector
is ARM Neon vector
Definition: Type.h:3381
clang::ObjCObjectPointerType::isObjCIdType
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:6341
clang::Sema::BuildBinOp
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15628
clang::Sema::CheckObjCConversion
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
Definition: SemaExprObjC.cpp:4386
clang::Sema::FilterLookupForScope
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1617
clang::Type::isFloatingType
bool isFloatingType() const
Definition: Type.cpp:2145
clang::Sema::AA_Assigning
@ AA_Assigning
Definition: Sema.h:3708
clang::LookupResult
Represents the results of name lookup.
Definition: Lookup.h:46
clang::ASTContext::getBaseElementType
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
Definition: ASTContext.cpp:7031
clang::Qualifiers
The collection of all-type qualifiers we support.
Definition: Type.h:146
clang::Sema::GetSignedSizelessVectorType
QualType GetSignedSizelessVectorType(QualType V)
Definition: SemaExpr.cpp:13149
clang::TargetInfo::getCXXABI
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1265
clang::ast_matchers::type
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchersInternal.cpp:774
clang::Declarator::getContext
DeclaratorContext getContext() const
Definition: DeclSpec.h:1994
clang::isUnresolvedExceptionSpec
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
Definition: ExceptionSpecificationType.h:49
clang::SourceLocExpr::SourceLocStruct
@ SourceLocStruct
Definition: Expr.h:4695
clang::ParmVarDecl
Represents a parameter to a function.
Definition: Decl.h:1724
clang::Sema::Diag
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1877
clang::Sema::GetTypeForDeclarator
TypeSourceInfo * GetTypeForDeclarator(Declarator &D, Scope *S)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5924
unsupportedTypeConversion
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, QualType RHSType)
Diagnose attempts to convert between __float128, __ibm128 and long double if there is no support for ...
Definition: SemaExpr.cpp:1245
clang::Redeclarable::getFirstDecl
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
clang::Sema::TUScope
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:1133
clang::Sema::CreateMaterializeTemporaryExpr
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8240
clang::VK_XValue
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:132
IsArithmeticBinaryExpr
static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, Expr **RHSExprs)
IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary expression, either using a built-i...
Definition: SemaExpr.cpp:9201
int
__device__ int
Definition: __clang_hip_libdevice_declares.h:63
clang::Expr::isModifiableLvalue
isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, does not have an incomplet...
Definition: ExprClassification.cpp:702
clang::FunctionDecl::setTemplateSpecializationKind
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4076
clang::TypeInfo::Width
uint64_t Width
Definition: ASTContext.h:153
clang::ASTContext::getFunctionType
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1532
clang::ObjCMethodDecl::getClassInterface
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1211
clang::Decl::isUsed
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:457
clang::ASTConsumer::HandleCXXImplicitFunctionInstantiation
virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D)
Invoked when a function is implicitly instantiated.
Definition: ASTConsumer.h:82
clang::Sema::VerifyIntegerConstantExpression
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17467
clang::Sema::BuildCallToObjectOfClassType
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
Definition: SemaOverload.cpp:14861
clang::Sema::CheckCompareOperands
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12621
clang::LookupResult::NotFoundInCurrentInstantiation
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
clang::Sema::CodeSynthesisContexts
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:9359
clang::SourceLocExpr::File
@ File
Definition: Expr.h:4695
clang::BinaryOperator::isAssignmentOp
bool isAssignmentOp() const
Definition: Expr.h:3953
clang::TemplateArgument::Declaration
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:73
clang::ASTContext::getBOOLDecl
TypedefDecl * getBOOLDecl() const
Retrieve declaration of 'BOOL' typedef.
Definition: ASTContext.h:2049
clang::BinaryOperator::getOpcodeStr
StringRef getOpcodeStr() const
Definition: Expr.h:3880
clang::ConversionFixItGenerator
The class facilities generation and storage of conversion FixIts.
Definition: SemaFixItUtils.h:32
clang::C99
@ C99
Definition: LangStandard.h:49
clang::FunctionProtoType::ExtProtoInfo::Variadic
bool Variadic
Definition: Type.h:4108
DiagnoseDivisionSizeofPointerOrArray
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10990
clang::Sema::DiscardCleanupsInEvaluationContext
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:18037
clang::FunctionDecl::isOverloadedOperator
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2726
clang::Expr::MLV_ArrayTemporary
@ MLV_ArrayTemporary
Definition: Expr.h:309
clang::Expr::EvalStatus::Diag
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:611
clang::ExprObjectKind
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:137
clang::Sema::CreateBuiltinBinOp
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
Definition: SemaExpr.cpp:15106
clang::Sema::getSourceManager
SourceManager & getSourceManager() const
Definition: Sema.h:1660
clang::Sema::CheckVectorCast
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:8079
clang::ICK_Array_To_Pointer
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
clang::Type::isRealFloatingType
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2161
clang::CleanupInfo::exprNeedsCleanups
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
clang::Sema::ExpressionEvaluationContext::DiscardedStatement
@ DiscardedStatement
The current expression occurs within a discarded statement.
ImmediateCallVisitor::VisitCallExpr
bool VisitCallExpr(CallExpr *E)
Definition: SemaExpr.cpp:5928
clang::Sema::LookupQualifiedName
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
Definition: SemaLookup.cpp:2418
clang::Sema::ActOnCastExpr
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:8167
BuildCookedLiteralOperatorCall
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr * > Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
Definition: SemaExpr.cpp:1822
clang::FunctionType::getExtInfo
ExtInfo getExtInfo() const
Definition: Type.h:3959
clang::Expr::IgnoreParenNoopCasts
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parenthese and casts which do not change the value (including ptr->int casts of the sam...
Definition: Expr.cpp:3063
checkPointerTypesForAssignment
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
Definition: SemaExpr.cpp:9485
DiagnoseBinOpPrecedence
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:15539
clang::Sema::tryToFixVariablyModifiedVarType
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
Definition: SemaDecl.cpp:6574
clang::StandardConversionSequence::setToType
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:334
clang::ComplexType::getElementType
QualType getElementType() const
Definition: Type.h:2733
clang::ASTContext::getCorrespondingSignedFixedPointType
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
Definition: ASTContext.cpp:13359
clang::InitListExpr
Describes an C or C++ initializer list.
Definition: Expr.h:4799
clang::sema::CapturingScopeInfo::addVLATypeCapture
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:710
clang::Sema::BuildPredefinedExpr
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK)
Definition: SemaExpr.cpp:3530
clang::ASTContext::OverloadTy
CanQualType OverloadTy
Definition: ASTContext.h:1106
clang::TargetInfo::hasFeature
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1382
checkArgsForPlaceholders
static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
Definition: SemaExpr.cpp:6609
clang::ComparisonCategoryType::First
@ First
checkPointerIntegerMismatch
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr)
Return false if the first expression is not an integer and the second expression is not a pointer,...
Definition: SemaExpr.cpp:8619
clang::Sema::CheckMatrixMultiplyOperands
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:13460
diagnoseFunctionPointerToVoidComparison
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:12061
diagnoseStringPlusInt
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
Definition: SemaExpr.cpp:11317
clang::ASTContext::getScalableVectorType
QualType getScalableVectorType(QualType EltTy, unsigned NumElts) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
Definition: ASTContext.cpp:4078
clang::CharacterLiteral::UTF8
@ UTF8
Definition: Expr.h:1601
clang::Sema::CheckLiteralKind
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
Definition: SemaExpr.cpp:12130
clang::Type::isVariableArrayType
bool isVariableArrayType() const
Definition: Type.h:6974
clang::Sema::UsualArithmeticConversions
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
Definition: SemaExpr.cpp:1528
clang::AvailabilitySpec::getVersion
VersionTuple getVersion() const
Definition: Availability.h:51
clang::Lexer::getSourceText
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:960
clang::UnaryOperator
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2175
clang::Expr::isPRValue
bool isPRValue() const
Definition: Expr.h:273
EnsureImmediateInvocationInDefaultArgs::TransformLambdaExpr
ExprResult TransformLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5977
clang::QualType::getAsString
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1089
diagnoseSubtractionOnNullPointer
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
Definition: SemaExpr.cpp:11163
SourceManager.h
clang::getLambdaAwareParentOfDeclContext
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:80
clang::NK_Type_Narrowing
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:236
clang::ImplicitConversionSequence::isFailure
bool isFailure() const
Definition: Overload.h:655
clang::Token::setIdentifierInfo
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:190
clang::Expr::NPC_NeverValueDependent
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:794
clang::Sema::isLaxVectorConversion
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
Definition: SemaExpr.cpp:8030
clang::FunctionDecl::isImplicitlyInstantiable
bool isImplicitlyInstantiable() const
Determines whether this function is a function template specialization or a member of a class templat...
Definition: Decl.cpp:3832
clang::Sema::AllowedExplicit::None
@ None
Allow no explicit functions to be used.
DiagnoseAdditionInShift
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:15497
clang::TargetInfo::getLongLongWidth
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:487
clang::Type::isVoidType
bool isVoidType() const
Definition: Type.h:7204
clang::FunctionDecl::isUserProvided
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2307
clang::Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
clang::Sema::FixOverloadedFunctionReference
Expr * FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
Definition: SemaOverload.cpp:15384
clang::Sema::DefineImplicitCopyConstructor
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
Definition: SemaDeclCXX.cpp:15246
clang::QualType::isVolatileQualified
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6718
Expression
clang::CPlusPlus14
@ CPlusPlus14
Definition: LangStandard.h:55
clang::Sema::CheckTransparentUnionArgumentConstraints
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:10119
clang::Sema::checkPseudoObjectAssignment
ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
Definition: SemaPseudoObject.cpp:1582
clang::Sema::BuildCallExpr
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6881
DeclSpec.h
clang::ASTContext::Char8Ty
CanQualType Char8Ty
Definition: ASTContext.h:1084
clang::Sema::ActOnPostfixUnaryOp
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4745
clang::Decl::getAttr
T * getAttr() const
Definition: DeclBase.h:556
clang::format::getBase
static Base getBase(const StringRef IntegerLiteral)
Definition: IntegerLiteralSeparatorFixer.cpp:22
clang::CXXScopeSpec
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:65
clang::InitializedEntity::InitializeParameter
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
Definition: Initialization.h:253
clang::sema::BlockScopeInfo::TheDecl
BlockDecl * TheDecl
Definition: ScopeInfo.h:757
ExprOpenMP.h
Designator.h
clang::ASTContext::getObjCIdRedefinitionType
QualType getObjCIdRedefinitionType() const
Retrieve the type that id has been defined to, which may be different from the built-in id if id has ...
Definition: ASTContext.h:1819
clang::Expr::containsUnexpandedParameterPack
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition: Expr.h:234
clang::Sema::DiagnoseAlwaysNonNullPointer
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
Definition: SemaChecking.cpp:14639
clang::Sema::BuildCallToMemberFunction
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
Definition: SemaOverload.cpp:14564
clang::Sema::LookupBuiltin
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:905
clang::AvailabilitySpec::getPlatform
StringRef getPlatform() const
Definition: Availability.h:52
clang::sema::Capture
Definition: ScopeInfo.h:536
clang::BinaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:3859
clang::Sema::DiscardMisalignedMemberAddress
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
Definition: SemaChecking.cpp:17667
clang::Sema::ResolveAndFixSingleFunctionTemplateSpecialization
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
Definition: SemaOverload.cpp:12843
clang::FunctionDecl::getCallResultType
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2674
ASTLambda.h
clang::DeclarationName::getAsIdentifierInfo
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
Definition: DeclarationName.h:419
clang::Sema::maybeExtendBlockObject
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
Definition: SemaExpr.cpp:7667
clang::CleanupInfo::reset
void reset()
Definition: CleanupInfo.h:33
clang::Sema::getStdNamespace
NamespaceDecl * getStdNamespace() const
Definition: SemaDeclCXX.cpp:11385
clang::Sema::TryCapture_ExplicitByRef
@ TryCapture_ExplicitByRef
Definition: Sema.h:5438
clang::getRewrittenOverloadedOperator
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
clang::InitializationSequence
Describes the sequence of initializations required to initialize a given object or reference with a s...
Definition: Initialization.h:788
clang::StringLiteral::Wide
@ Wide
Definition: Expr.h:1801
clang::ASTContext::getFixedPointMax
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
Definition: ASTContext.cpp:13349
clang::IdentifierInfo::getTokenID
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
Definition: IdentifierTable.h:262
clang::Qualifiers::compatiblyIncludes
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:531
clang::Sema::ActOnStmtExpr
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16134
clang::FunctionType
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3682
clang::CompoundStmt::body_empty
bool body_empty() const
Definition: Stmt.h:1462
clang::Sema::ExprEvalContexts
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1403
clang::BinaryOperator::isRelationalOp
bool isRelationalOp() const
Definition: Expr.h:3909
clang::sema::BlockScopeInfo
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:755
clang::Sema::getCurCapturedRegion
sema::CapturedRegionScopeInfo * getCurCapturedRegion()
Retrieve the current captured region, if any.
Definition: Sema.cpp:2685
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
clang::Sema::PopDeclContext
void PopDeclContext()
Definition: SemaDecl.cpp:1351
clang::CallExpr::ADLCallKind::NotADL
@ NotADL
clang::FunctionDecl::getMemberSpecializationInfo
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:3788
getParentOfCapturingContextOrNull
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18622
clang::Expr::IgnoreImpCasts
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3016
LiteralSupport.h
clang::Expr::EvalResult::Val
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:626
clang::ObjCObjectPointerType::getInterfaceDecl
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:6335
clang::Sema::BuildLiteralOperatorCall
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
Definition: SemaOverload.cpp:15234
clang::TemplateArgument::getAsExpr
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:368
clang::FunctionDecl::param_size
size_t param_size() const
Definition: Decl.h:2600
clang::DeclarationName
The name of a declaration.
Definition: DeclarationName.h:144
clang::Sema::LOLR_Error
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:4365
End
SourceLocation End
Definition: USRLocFinder.cpp:167
isPlaceholderToRemoveAsArg
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
Definition: SemaExpr.cpp:6547
clang::Sema::CheckPtrComparisonWithNullChar
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
Definition: SemaExpr.cpp:12594
clang::TypoCorrection::getCorrection
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
Definition: TypoCorrection.h:84
clang::OMPIteratorExpr::Create
static OMPIteratorExpr * Create(const ASTContext &Context, QualType T, SourceLocation IteratorKwLoc, SourceLocation L, SourceLocation R, ArrayRef< IteratorDefinition > Data, ArrayRef< OMPIteratorHelperData > Helpers)
Definition: Expr.cpp:5087
clang::Sema::PendingInstantiations
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:9823
clang::Sema::OffsetOfComponent
Definition: Sema.h:5954
clang::Sema::ConditionKind
ConditionKind
Definition: Sema.h:12825
IgnoreCommaOperand
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
Definition: SemaExpr.cpp:14244
clang::DeclRefExpr::copyTemplateArgumentsInto
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition: Expr.h:1392
clang::ASTContext::getTranslationUnitDecl
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1060
clang::sema::LambdaScopeInfo::CallOperator
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:839
clang::Qualifiers::compatiblyIncludesObjCLifetime
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:552
clang::LookupResult::begin
iterator begin() const
Definition: Lookup.h:335
clang::ASTContext::Char16Ty
CanQualType Char16Ty
Definition: ASTContext.h:1085
clang::LookupResult::getNameLoc
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:632
clang::ArrayType::Normal
@ Normal
Definition: Type.h:3026
clang::Sema::IntToPointer
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition: Sema.h:12367
clang::TemplateArgument::Expression
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:95
clang::sema::Capture::isCopyCapture
bool isCopyCapture() const
Definition: ScopeInfo.h:625
clang::BinaryOperator::isNullPointerArithmeticExtension
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, Expr *LHS, Expr *RHS)
Definition: Expr.cpp:2195
clang::Expr::isGLValue
bool isGLValue() const
Definition: Expr.h:275
clang::Decl::markUsed
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:472
clang::Sema::checkUnsafeExprAssigns
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
Definition: SemaChecking.cpp:16958
clang::Sema::ActOnBlockError
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
Definition: SemaExpr.cpp:16577
clang::ICK_Complex_Conversion
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:139
clang::sema::FunctionScopeInfo::setHasBranchProtectedScope
void setHasBranchProtectedScope()
Definition: ScopeInfo.h:429
clang::ASTContext::getFixedPointScale
unsigned char getFixedPointScale(QualType Ty) const
Definition: ASTContext.cpp:13246
clang::Expr::findBoundMemberType
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition: Expr.cpp:2992
clang::sema::CapturedRegionScopeInfo
Retains information about a captured region.
Definition: ScopeInfo.h:781
clang::Preprocessor::getIdentifierTable
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:1208
clang::Sema::isUnevaluatedContext
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:9670
clang::Sema::CheckCaseExpression
bool CheckCaseExpression(Expr *E)
Definition: SemaExpr.cpp:21108
clang::Sema::ExpressionEvaluationContextRecord::EK_Decltype
@ EK_Decltype
Definition: Sema.h:1331
Paren
@ Paren
Definition: PPMacroExpansion.cpp:638
clang::CC_X86StdCall
@ CC_X86StdCall
Definition: Specifiers.h:268
clang::Sema::CheckAssignmentOperands
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:14112
clang::FunctionDecl::isConsteval
bool isConsteval() const
Definition: Decl.h:2379
clang::Type::hasFloatingRepresentation
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2154
clang::Sema::CVT_Device
@ CVT_Device
Definition: Sema.h:13066
clang::getTraitSpelling
const char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
Definition: ExpressionTraits.cpp:33
clang::FunctionProtoType::isVariadic
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4356
clang::Type::STK_Integral
@ STK_Integral
Definition: Type.h:2289
clang::Sema::DiagnoseDependentMemberLookup
bool DiagnoseDependentMemberLookup(LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2209
clang::OpaqueValueExpr
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1147
clang::Preprocessor::getLangOpts
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:1201
clang::Sema::Context
ASTContext & Context
Definition: Sema.h:409
clang::Sema::CheckUnevaluatedOperand
ExprResult CheckUnevaluatedOperand(Expr *E)
Definition: SemaExprCXX.cpp:8216
clang::ASTContext::OMPIteratorTy
CanQualType OMPIteratorTy
Definition: ASTContext.h:1117
clang::Type
The base class of the type hierarchy.
Definition: Type.h:1566
Preprocessor.h
clang::Sema::RebuildingImmediateInvocation
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:1044
clang::Sema::IncompatibleObjCQualifiedId
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:12430
clang::Sema::GetTypeForDeclaratorCast
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:6037
Overload.h
clang::Sema::BuildInitList
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7641
clang::Sema::ConditionKind::Switch
@ Switch
An integral condition for a 'switch' statement.
clang::FunctionDecl::isInlined
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2714
clang::ObjCBoolLiteralExpr
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:87
clang::FunctionDecl::hasPrototype
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2340
clang::Decl::getAvailability
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:636
clang::Sema::AA_Sending
@ AA_Sending
Definition: Sema.h:3713
clang::Type::hasSignedIntegerRepresentation
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2082
clang::Sema::anyAltivecTypes
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7978
clang::ExprError
ExprResult ExprError()
Definition: Ownership.h:278
clang::Sema::ActOnStringLiteral
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
Definition: SemaExpr.cpp:1858
clang::Sema::ResolveAddressOfOverloadedFunction
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
Definition: SemaOverload.cpp:12599
clang::LookupResult::addDecl
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:452
clang::Sema::CheckCXXDefaultArgExpr
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5868
clang::ASTContext::ARCUnbridgedCastTy
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1108
clang::OMPIteratorHelperData::CounterVD
VarDecl * CounterVD
Internal normalized counter.
Definition: ExprOpenMP.h:237
clang::ConditionalOperator
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4153
clang::OverloadExpr::find
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3014
clang::UnaryOperator::getOverloadedOperator
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1413
clang::Sema::ExprCleanupObjects
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:790
clang::TypedefType
Definition: Type.h:4542
clang::ObjCObjectType
Represents a class type in Objective C.
Definition: Type.h:6028
clang::FullExpr
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:1016
ParentMapContext.h
clang::Type::isExtVectorType
bool isExtVectorType() const
Definition: Type.h:7002
DeclObjC.h
clang::Sema::DefineImplicitDestructor
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
Definition: SemaDeclCXX.cpp:13870
Offset
unsigned Offset
Definition: Format.cpp:2775
clang::Sema::CheckCallReturnType
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
Definition: SemaExpr.cpp:20231
clang::QualType::isAddressSpaceOverlapping
bool isAddressSpaceOverlapping(QualType T) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition: Type.h:1173
clang::Expr::MLV_ArrayType
@ MLV_ArrayType
Definition: Expr.h:303
clang::Sema::DiagnoseEmptyLookup
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2271
clang::CXXScopeSpec::isSet
bool isSet() const
Deprecated.
Definition: DeclSpec.h:211
clang::AS_none
@ AS_none
Definition: Specifiers.h:115
clang::Sema::DiagnoseAssignmentResult
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:17133
clang::LookupResult::isUnresolvableResult
bool isUnresolvableResult() const
Definition: Lookup.h:317
clang::ParenListExpr::Create
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4564
GetFixedPointRank
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1384
clang::CPlusPlus17
@ CPlusPlus17
Definition: LangStandard.h:56
clang::TypeLoc::getBeginLoc
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:191
clang::FixItHint
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
clang::sema::CapturedRegionScopeInfo::CapRegionKind
unsigned short CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:796
clang::FunctionType::getCmseNSCallAttr
bool getCmseNSCallAttr() const
Definition: Type.h:3957
clang::ASTContext::typesAreCompatible
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
Definition: ASTContext.cpp:10213
clang::Expr::MLV_LValueCast
@ MLV_LValueCast
Definition: Expr.h:298
clang::ASTContext::getBlockPointerType
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
Definition: ASTContext.cpp:3478
clang::Sema::ComparisonCategoryUsage::OperatorInExpression
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
clang::ASTContext::BoundMemberTy
CanQualType BoundMemberTy
Definition: ASTContext.h:1106
clang::Sema::getLangOpts
const LangOptions & getLangOpts() const
Definition: Sema.h:1655
clang::Type::isObjCBuiltinType
bool isObjCBuiltinType() const
Definition: Type.h:7075
clang::Expr::getIntegerConstantExpr
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Definition: ExprConstant.cpp:16019
clang::FunctionParmPackExpr
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4480
clang::Sema::ICEConvertDiagnoser
Definition: Sema.h:3915
clang::ObjCIvarRefExpr::getDecl
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:576
maybeDiagnoseAssignmentToFunction
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:17114
clang::Sema::CheckMatrixElementwiseOperands
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
Definition: SemaExpr.cpp:13414
clang::ASTContext::ObjCBuiltinBoolTy
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1110
clang::sema::LambdaScopeInfo::Lambda
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:836
clang::Qualifiers::getAddressSpace
LangAS getAddressSpace() const
Definition: Type.h:377
clang::Sema::ExpressionEvaluationContextRecord::Lambdas
SmallVector< LambdaExpr *, 2 > Lambdas
The lambdas that are present within this context, if it is indeed an unevaluated context.
Definition: Sema.h:1299
clang::Sema::BuildBuiltinOffsetOf
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:16209
NCCK_Block
@ NCCK_Block
Definition: SemaExpr.cpp:13691
clang::Sema::BuildOverloadedCallExpr
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
Definition: SemaOverload.cpp:13494
clang::dataflow::Literal
uint32_t Literal
Literals are represented as positive integers.
Definition: WatchedLiteralsSolver.cpp:55
clang::ObjCObjectPointerType::quals
qual_range quals() const
Definition: Type.h:6402
clang::Sema::ActOnBlockArguments
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:16459
APSInt
llvm::APSInt APSInt
Definition: ByteCodeEmitter.cpp:20
clang::ExprEmpty
ExprResult ExprEmpty()
Definition: Ownership.h:289
ImmediateCallVisitor::VisitCXXDefaultArgExpr
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E)
Definition: SemaExpr.cpp:5959
clang::QualType::isAtLeastAsQualifiedAs
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:6825
checkBlockPointerTypesForAssignment
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:9635
U
clang::Sema::getVariadicCallType
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:6160
clang::LookupResult::resolveKind
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:482
clang::ASTContext::isPromotableIntegerType
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
Definition: ASTContext.cpp:1942
clang::DeclRefExpr::getTemplateKeywordLoc
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: Expr.h:1360
clang::Sema::ImmediateInvocationCandidate
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition: Sema.h:1276
clang::Sema::VarArgKind
VarArgKind
Definition: Sema.h:12285
checkVectorShift
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Return the resulting type when a vector is shifted by a scalar or vector shift amount.
Definition: SemaExpr.cpp:11771
clang::Sema::ActOnArraySubscriptExpr
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:4820
clang::OverloadExpr::FindResult
Definition: ExprCXX.h:3003
clang::ParmVarDecl::setScopeInfo
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1757
clang::CharSourceRange::getCharRange
static CharSourceRange getCharRange(SourceRange R)
Definition: SourceLocation.h:265
clang::Sema::getCurFunctionDecl
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false)
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1457
clang::CUDAKernelCallExpr::Create
static CUDAKernelCallExpr * Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:1802
clang::ASTContext::getReferenceQualifiedType
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
Definition: ASTContext.cpp:5745
clang::Sema::CheckBitwiseOperands
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13511
clang::Sema::LookupMemberName
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:4296
clang::VarDecl::isInline
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1503
OEK_Variable
@ OEK_Variable
Definition: SemaExpr.cpp:13870
clang::FunctionTemplateDecl
Declaration of a template function.
Definition: DeclTemplate.h:1005
clang::Expr::isKnownToHaveBooleanValue
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:137
clang::Sema::RequireCompleteType
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8722
clang::GenericSelectionExpr::Create
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression.
Definition: Expr.cpp:4351
clang::ASTContext::getObjCIdType
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2018
clang::sema::CapturingScopeInfo::addCapture
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:702
llvm::MutableArrayRef
Definition: LLVM.h:32
clang::CXXOperatorCallExpr::getOperatorLoc
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition: ExprCXX.h:149
clang::Sema::CheckDerivedToBaseConversion
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
Definition: SemaDeclCXX.cpp:3046
DiagnoseShiftCompare
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15511
clang::Sema::ExpressionEvaluationContextRecord::ImmediateInvocationCandidates
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition: Sema.h:1322
clang::Sema::DiagnoseInvalidJumps
void DiagnoseInvalidJumps(Stmt *Body)
Definition: JumpDiagnostics.cpp:1018
EnsureImmediateInvocationInDefaultArgs::EnsureImmediateInvocationInDefaultArgs
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
Definition: SemaExpr.cpp:5970
clang::TypeLocBuilder::push
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
Definition: TypeLocBuilder.h:99
clang::Type::isReferenceType
bool isReferenceType() const
Definition: Type.h:6908
clang::Sema::CreateOverloadedArraySubscriptExpr
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
Definition: SemaOverload.cpp:14371
clang::Sema::CheckRemainderOperands
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11090
clang::Sema::CheckVecStepExpr
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4475
clang::CallExpr::getCallee
Expr * getCallee()
Definition: Expr.h:2963
clang::Type::isObjCClassType
bool isObjCClassType() const
Definition: Type.h:7063
clang::TSK_ExplicitInstantiationDeclaration
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:190
V
#define V(N, I)
Definition: ASTContext.h:3212
clang::VarDecl::hasInit
bool hasInit() const
Definition: Decl.cpp:2327
clang::IntegerLiteral
Definition: Expr.h:1506
clang::Sema::BuildAnonymousStructUnionMemberReference
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
Definition: SemaExprMember.cpp:802
clang::Type::STK_BlockPointer
@ STK_BlockPointer
Definition: Type.h:2285
clang::Sema::VariadicFunction
@ VariadicFunction
Definition: Sema.h:12272
Template.h
clang::LangOptions::LaxVectorConversionKind::Integer
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
clang::Type::isSaturatedFixedPointType
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7261
clang::StandardConversionSequence::setAsIdentityConversion
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
Definition: SemaOverload.cpp:196
clang::ASTContext::getExtVectorType
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
Definition: ASTContext.cpp:4192
MarkExprReferenced
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19936
clang::ParenListExpr::getLParenLoc
SourceLocation getLParenLoc() const
Definition: Expr.h:5427
clang::FunctionDecl::setInstantiationIsPending
void setInstantiationIsPending(bool IC)
State that the instantiation of this function is pending.
Definition: Decl.h:2395
clang::Type::isBitIntType
bool isBitIntType() const
Definition: Type.h:7120
clang::ast_matchers::attr
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
Definition: ASTMatchersInternal.cpp:1032
clang::Sema::LookupMethodInQualifiedType
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
Definition: SemaExprObjC.cpp:1958
clang::UnaryExprOrTypeTraitExpr
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2561
isMSPropertySubscriptExpr
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4779
clang::TypeLocBuilder::pushTypeSpec
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
Definition: TypeLocBuilder.h:73
clang::Sema::BuildIvarRefExpr
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
Definition: SemaExpr.cpp:2901
clang::Sema::isQualifiedMemberAccess
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:16020
clang::Sema::ExpressionEvaluationContext::UnevaluatedList
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
clang::Expr::isTypeDependent
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:187
clang::Sema::ActOnObjCAvailabilityCheckExpr
ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef< AvailabilitySpec > AvailSpecs, SourceLocation AtLoc, SourceLocation RParen)
Definition: SemaExpr.cpp:21137
clang::BinaryOperator::isEqualityOp
bool isEqualityOp() const
Definition: Expr.h:3912
clang::InitializedEntity::InitializeCompoundLiteralInit
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI)
Create the entity for a compound literal initializer.
Definition: Initialization.h:419
clang::Sema::FindCompositePointerType
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
Definition: SemaExprCXX.cpp:6784
clang::CallExpr::getDirectCallee
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2983
ConstVariable
@ ConstVariable
Definition: SemaExpr.cpp:13739
clang::RecordType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4823
clang::TemplateArgument::getKind
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:263
rewriteBuiltinFunctionDecl
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, FunctionDecl *FDecl, MultiExprArg ArgExprs)
If a builtin function has a pointer argument with no explicit address space, then it should be able t...
Definition: SemaExpr.cpp:6634
clang::CompoundStmt
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1418
clang::Sema::computeNRVO
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
Definition: SemaDecl.cpp:15308
clang::FunctionType::getNoReturnAttr
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:3955
clang::InitializedEntity::InitializeStmtExprResult
static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc, QualType Type)
Definition: Initialization.h:304
clang::Sema::VariadicDoesNotApply
@ VariadicDoesNotApply
Definition: Sema.h:12276
clang::Sema::CurFPFeatures
FPOptions CurFPFeatures
Definition: Sema.h:405
DeclTemplate.h
clang::MSPropertySubscriptExpr
MS property subscript expression.
Definition: ExprCXX.h:1000
clang::Sema::inTemplateInstantiation
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:9641
clang::ASTContext::removeAddrSpaceQualType
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
Definition: ASTContext.cpp:3159
checkBlockType
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:8824
clang::ASTContext::areCompatibleSveTypes
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
Definition: ASTContext.cpp:9507
clang::interp::Opcode
Opcode
Definition: Opcode.h:21
clang::VectorType::SveFixedLengthDataVector
@ SveFixedLengthDataVector
is AArch64 SVE fixed-length data vector
Definition: Type.h:3387
clang::Sema::UPPC_Block
@ UPPC_Block
Block expression.
Definition: Sema.h:8648
clang::UnresolvedLookupExpr
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3147
clang::Sema::EmitRelatedResultTypeNoteForReturn
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
Definition: SemaExprObjC.cpp:1655
clang::TypoCorrection::getAsString
std::string getAsString(const LangOptions &LO) const
Definition: SemaLookup.cpp:5556
clang::Selector::getNameForSlot
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
Definition: IdentifierTable.cpp:585
clang::ASTContext::WideCharTy
CanQualType WideCharTy
Definition: ASTContext.h:1082
clang::Type::isNonOverloadPlaceholderType
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:7198
clang::PartialDiagnosticAt
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
Definition: PartialDiagnostic.h:205
clang::Sema::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1659
clang::LambdaExpr::getCallOperator
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Definition: ExprCXX.cpp:1326
clang::OMPIteratorExpr::IteratorDefinition::ColonLoc
SourceLocation ColonLoc
Definition: ExprOpenMP.h:288
clang::CXXMethodDecl::isInstance
bool isInstance() const
Definition: DeclCXX.h:2022
clang::TemplateArgumentListInfo
A convenient class for passing around template argument information.
Definition: TemplateBase.h:590
clang::Expr::NPC_ValueDependentIsNull
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:798
clang::ASTContext::AccumTy
CanQualType AccumTy
Definition: ASTContext.h:1091
clang::Sema::MarkAnyDeclReferenced
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20031
clang::Declarator::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2005
clang::SourceLocExpr::Line
@ Line
Definition: Expr.h:4695
clang::LangOptions::ObjCRuntime
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:417
clang::ASTContext::getAsConstantArrayType
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2698
clang::QualType::getNonLValueExprType
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3163
clang::CharacterLiteral::Wide
@ Wide
Definition: Expr.h:1600
clang::DeclAccessPair::make
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
Definition: DeclAccessPair.h:35
clang::Sema::ACR_okay
@ ACR_okay
Definition: Sema.h:12731
clang::DeclRefExpr::Create
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:536
clang::ConversionFixItGenerator::tryToFixConversion
bool tryToFixConversion(const Expr *FromExpr, const QualType FromQTy, const QualType ToQTy, Sema &S)
If possible, generates and stores a fix for the given conversion.
Definition: SemaFixItUtils.cpp:50
clang::Sema::CurFPFeatureOverrides
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:705
clang::FunctionDecl::isTrivial
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2274
clang::ASTContext::getNameForTemplate
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
Definition: ASTContext.cpp:6242
clang::Expr::MLV_ClassTemporary
@ MLV_ClassTemporary
Definition: Expr.h:308
clang::Sema::CFT_HostDevice
@ CFT_HostDevice
Definition: Sema.h:13052
clang::Sema::diagnoseARCUnbridgedCast
void diagnoseARCUnbridgedCast(Expr *e)
Given that we saw an expression with the ARCUnbridgedCastTy placeholder type, complain bitterly.
Definition: SemaExprObjC.cpp:4506
clang::Sema::CheckMatrixCast
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
Definition: SemaExpr.cpp:8058
clang::Sema::ActOnChooseExpr
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16391
clang::BlockDecl
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4332
clang::UnresolvedMemberExpr::isImplicitAccess
bool isImplicitAccess() const
True if this is an implicit access, i.e., one in which the member being accessed was not written in t...
Definition: ExprCXX.cpp:1559
clang::QualType::getAddressSpace
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6769
clang::Sema::EmitRelatedResultTypeNote
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
Definition: SemaExprObjC.cpp:1684
clang::DependentScopeDeclRefExpr::Create
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:479
clang::Decl::getKind
Kind getKind() const
Definition: DeclBase.h:435
clang::Sema::ActOnBuiltinOffsetOf
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:16372
clang::ParenExpr::getSubExpr
const Expr * getSubExpr() const
Definition: Expr.h:2139
clang::Sema::ACK_BitwiseOp
@ ACK_BitwiseOp
A bitwise operation.
Definition: Sema.h:12335
clang::BinaryOperator
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3815
clang::Sema::CheckObjCBridgeRelatedConversions
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExprObjC.cpp:4293
clang::ConversionFixItGenerator::Hints
std::vector< FixItHint > Hints
The list of Hints generated so far.
Definition: SemaFixItUtils.h:41
clang::Sema::CreateParsedType
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6574
Id
int Id
Definition: ASTDiff.cpp:190
clang::Sema::CheckObjCBridgeRelatedCast
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr)
Definition: SemaExprObjC.cpp:4181
clang::Preprocessor::getSpellingOfSingleCharacterNumericConstant
char getSpellingOfSingleCharacterNumericConstant(const Token &Tok, bool *Invalid=nullptr) const
Given a Token Tok that is a numeric constant with length 1, return the character.
Definition: Preprocessor.h:2106
DiagnoseBitwisePrecedence
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison operators are mixed in a way t...
Definition: SemaExpr.cpp:15391
ShouldLookupResultBeMultiVersionOverload
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3218
clang::toTargetAddressSpace
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:78
clang::TemplateArgumentListInfo::addArgument
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:630
clang::Qualifiers::OCL_Strong
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:174
hlsl::uint64_t
unsigned long uint64_t
Definition: hlsl_basic_types.h:25
clang::XRayInstrKind::None
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
clang::Type::isNullPtrType
bool isNullPtrType() const
Definition: Type.h:7229
clang::Sema::StdSourceLocationImplDecl
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition: Sema.h:1170
clang::LambdaExpr
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1923
clang::Scope
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
convertHalfVecBinOp
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptionsOverride FPFeatures)
Definition: SemaExpr.cpp:15023
clang::ASTContext::Float16Ty
CanQualType Float16Ty
Definition: ASTContext.h:1104
clang::Expr::ClassifyLValue
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
Definition: ExprClassification.cpp:682
clang::CXXScopeSpec::isValid
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:198
clang::Sema::ExpressionEvaluationContextRecord::SavedMaybeODRUseExprs
MaybeODRUseExprSet SavedMaybeODRUseExprs
Definition: Sema.h:1295
clang::DeclarationName::CXXDestructorName
@ CXXDestructorName
Definition: DeclarationName.h:213
clang::Type::isObjCIdType
bool isObjCIdType() const
Definition: Type.h:7057
clang::ASTContext::getAsArrayType
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
Definition: ASTContext.cpp:6920
clang::CallExpr::getArgs
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:2994
clang::Sema::LookupName
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
Definition: SemaLookup.cpp:2179
clang::SourceRange::getEnd
SourceLocation getEnd() const
Definition: SourceLocation.h:220
TryTypoCorrectionForCall
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
Definition: SemaExpr.cpp:6204
clang::TargetInfo::getPointerWidth
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:440
clang::Type::isAnyCharacterType
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2021
clang::sema::Capture::getCaptureType
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:666
clang::Sema::AssumedTemplateKind
AssumedTemplateKind
Definition: Sema.h:8008
clang::QualType::getAtomicUnqualifiedType
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition: Type.cpp:1531
clang::Sema::RequireNonAbstractType
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Definition: SemaDeclCXX.cpp:5827
clang::Sema::VariadicCallType
VariadicCallType
Definition: Sema.h:12271
clang::Expr::LV_Valid
@ LV_Valid
Definition: Expr.h:278
clang::Type::isFunctionPointerType
bool isFunctionPointerType() const
Definition: Type.h:6930
clang::Sema::CheckComparisonCategoryType
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
Definition: SemaDeclCXX.cpp:11437
getDependentArraySubscriptType
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
Definition: SemaExpr.cpp:4798
clang::Sema::PendingLocalImplicitInstantiations
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:9882
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:91
clang::DeclAccessPair
A POD class for pairing a NamedDecl* with an access specifier.
Definition: DeclAccessPair.h:29
clang::VectorType
Represents a GCC generic vector type.
Definition: Type.h:3365
clang::OMF_dealloc
@ OMF_dealloc
Definition: IdentifierTable.h:714
clang::VarDecl::getMemberSpecializationInfo
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2786
clang::FunctionDecl::getReturnTypeSourceRange
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3640
clang::Sema::VariadicConstructor
@ VariadicConstructor
Definition: Sema.h:12275
clang::sema::CapturingScopeInfo::ImpCap_None
@ ImpCap_None
Definition: ScopeInfo.h:675
clang::ASTContext::DependentTy
CanQualType DependentTy
Definition: ASTContext.h:1106
clang::Sema::PushDeclContext
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1344
clang::OMPIteratorExpr::IteratorRange::Begin
Expr * Begin
Definition: ExprOpenMP.h:279
clang::VarDecl::isStaticDataMember
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1242
clang::ObjCMethodDecl::getMethodFamily
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:1053
clang::Sema::DefaultFunctionArrayConversion
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:506
clang::FPOptionsOverride
Represents difference between two FPOptions values.
Definition: LangOptions.h:806
clang::SC_Extern
@ SC_Extern
Definition: Specifiers.h:239
clang::Token::getKind
tok::TokenKind getKind() const
Definition: Token.h:93
ImmediateCallVisitor::VisitSourceLocExpr
bool VisitSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5938
CheckExtensionTraitOperandType
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4191
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
clang::DeclaratorDecl::getQualifierLoc
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:833
clang::ASTContext::getSizeType
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Definition: ASTContext.cpp:5977
clang::BlockDecl::setBody
void setBody(CompoundStmt *B)
Definition: Decl.h:4412
clang::ExprResult
ActionResult< Expr * > ExprResult
Definition: Ownership.h:262
clang::CPlusPlus
@ CPlusPlus
Definition: LangStandard.h:53
clang::Sema::CheckForConstantInitializer
bool CheckForConstantInitializer(Expr *e, QualType t)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12191
clang::sema::Capture::isInvalid
bool isInvalid() const
Definition: ScopeInfo.h:632
clang::ArrayType
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3019
clang::Sema::getCurFunctionOrMethodDecl
NamedDecl * getCurFunctionOrMethodDecl()
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1469
clang::AttributedType::getNullabilityAttrKind
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:4931
clang::Sema::TryCapture_Implicit
@ TryCapture_Implicit
Definition: Sema.h:5438
checkArithmeticOrEnumeralThreeWayCompare
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12485
clang::Expr::hasPlaceholderType
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:504
clang::ASTContext::getFloatingTypeOrder
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
Definition: ASTContext.cpp:7099
clang::DeclaratorContext::Member
@ Member
clang::ConstantMatrixType
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:3591
clang::Sema::LK_Dictionary
@ LK_Dictionary
Definition: Sema.h:3954
clang::DeclarationName::getAsString
std::string getAsString() const
Retrieve the human-readable string for this name.
Definition: DeclarationName.cpp:229
Std
LangStandard::Kind Std
Definition: InterpolatingCompilationDatabase.cpp:133
clang::Qualifiers::getCVRQualifiers
unsigned getCVRQualifiers() const
Definition: Type.h:294
clang::RecursiveASTVisitor
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Definition: RecursiveASTVisitor.h:152
diagnoseArithmeticOnTwoVoidPointers
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:11128
clang::Sema::ExpressionEvaluationContextRecord::NumTypos
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:1293
checkOpenCLConditionVector
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:8738
clang::TypoCorrection::getFoundDecl
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
Definition: TypoCorrection.h:146
clang::CallExpr::setArg
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3017
clang::LangOptions::FPEvalMethodKind
FPEvalMethodKind
Possible float expression evaluation method choices.
Definition: LangOptions.h:282
clang::FunctionDecl::getBody
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3118
clang::Expr::NPCK_ZeroLiteral
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:781
clang::Sema::FullExprArg
Definition: Sema.h:4979
clang::sema::FunctionScopeInfo::AddrLabels
llvm::SmallVector< AddrLabelExpr *, 4 > AddrLabels
The set of GNU address of label extension "&&label".
Definition: ScopeInfo.h:237
clang::QualType::isNonWeakInMRRWithObjCWeak
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2565
clang::Sema::PointerToInt
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition: Sema.h:12363
clang::Sema::ExpressionEvaluationContextRecord::ExprContext
enum clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext
checkArithmeticOpPointerOperand
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:11232
clang::QualType::isCXX98PODType
bool isCXX98PODType(const ASTContext &Context) const
Return true if this is a POD type according to the rules of the C++98 standard, regardless of the cur...
Definition: Type.cpp:2406
clang::Type::getAs
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7410
clang::Type::isComplexType
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:605
clang::OMPIteratorHelperData::CounterUpdate
Expr * CounterUpdate
Updater for the internal counter: ++CounterVD;.
Definition: ExprOpenMP.h:245
clang::Sema::ExpressionEvaluationContextRecord::PossibleDerefs
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:1314
clang::QualType::DK_none
@ DK_none
Definition: Type.h:1277
clang::CXXRecordDecl::getNumBases
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:596
clang::OK_BitField
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:142
clang::Sema::VariadicBlock
@ VariadicBlock
Definition: Sema.h:12273
clang::Decl::isInvalidDecl
bool isInvalidDecl() const
Definition: DeclBase.h:571
clang::PredefinedExpr::LFunction
@ LFunction
Definition: Expr.h:1985
clang::Sema::ExpressionEvaluationContext::Unevaluated
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
clang::CallExpr::getArg
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3004
clang::ObjCIvarRefExpr::getOpLoc
SourceLocation getOpLoc() const
Definition: ExprObjC.h:597
checkAddressOfFunctionIsAvailable
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
Definition: SemaOverload.cpp:10467
clang::TemplateArgument
Represents a template argument.
Definition: TemplateBase.h:60
clang::Sema::checkSpecializationReachability
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
Definition: SemaTemplate.cpp:11502
clang::StringLiteral::UTF32
@ UTF32
Definition: Expr.h:1801
clang::Sema::InnermostDeclarationWithDelayedImmediateInvocations
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:9698
OpenCLCheckVectorConditional
static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Return the resulting type for the conditional operator in OpenCL (aka "ternary selection operator",...
Definition: SemaExpr.cpp:8786
clang::Sema::DiagnoseUnexpandedParameterPack
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
Definition: SemaTemplateVariadic.cpp:399
clang::Sema::ShouldSplatAltivecScalarInCast
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
Definition: SemaCast.cpp:2645
clang::ObjCInterfaceDecl::lookupInstanceVariable
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:638
clang::DeclarationName::CXXOperatorName
@ CXXOperatorName
Definition: DeclarationName.h:215
clang::ASTContext::BuiltinVectorTypeInfo::EC
llvm::ElementCount EC
Definition: ASTContext.h:1460
clang::Sema::AssignConvertType
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:12357
convertVector
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S)
Convert vector E to a vector with the same number of elements but different element type.
Definition: SemaExpr.cpp:10459
clang::Sema::DefaultedComparisonKind::None
@ None
This is not a defaultable comparison operator.
clang::ObjCAvailabilityCheckExpr
A runtime availability query.
Definition: ExprObjC.h:1685
clang::Sema::PerformContextuallyConvertToBool
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
Definition: SemaOverload.cpp:5696
clang::Expr::containsErrors
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:240
clang::Preprocessor::Diag
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
Definition: Preprocessor.h:2038
clang::DeclContext::containsDecl
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1476
clang::Sema::Diags
DiagnosticsEngine & Diags
Definition: Sema.h:411
clang::Sema::BuildSourceLocExpr
ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:17050
clang::Type::isVectorType
bool isVectorType() const
Definition: Type.h:6998
clang::OMPArraySectionExpr::getBaseOriginalType
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition: Expr.cpp:4877
clang::FunctionProtoType::getParamType
QualType getParamType(unsigned i) const
Definition: Type.h:4236
clang::ParmVarDecl::hasUnparsedDefaultArg
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1841
clang::Sema::DiagRuntimeBehavior
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20225
clang::DeclaratorContext::BlockLiteral
@ BlockLiteral
isVariableCapturable
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18641
clang::Sema::PushBlockScope
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2129
clang::Type::getSveEltType
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2385
clang::LabelDecl
Represents the declaration of a label.
Definition: Decl.h:496
clang::Expr::MLV_NotObjectType
@ MLV_NotObjectType
Definition: Expr.h:294
clang::ObjCMethodDecl::getSelfDecl
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:420
clang::Sema::ConditionError
static ConditionResult ConditionError()
Definition: Sema.h:12823
clang::Sema::CheckCompleteDestructorVariant
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
Definition: SemaDeclCXX.cpp:13912
clang::PseudoObjectExpr
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:5945
clang::Expr::MLV_InvalidExpression
@ MLV_InvalidExpression
Definition: Expr.h:297
DelayedDiagnostic.h
clang::Decl::getCanonicalDecl
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:943
clang::Sema::ActOnBlockStart
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:16430
clang::CallExpr::setNumArgsUnsafe
void setNumArgsUnsafe(unsigned NewNumArgs)
Bluntly set a new number of arguments without doing any checks whatsoever.
Definition: Expr.h:3045
clang::Sema::VerifyICEDiagnoser::diagnoseNotICEType
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
Definition: SemaExpr.cpp:17456
clang::ASTContext::getBuiltinVectorTypeInfo
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
Definition: ASTContext.cpp:3950
clang::ASTContext::UnknownAnyTy
CanQualType UnknownAnyTy
Definition: ASTContext.h:1106
clang::Expr::EvaluateAsConstantExpr
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
Definition: ExprConstant.cpp:15318
clang::Sema::ACK_Arithmetic
@ ACK_Arithmetic
An arithmetic operation.
Definition: Sema.h:12333
clang::Preprocessor::getTargetInfo
const TargetInfo & getTargetInfo() const
Definition: Preprocessor.h:1202
clang::IntegerLiteral::Create
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:983
CastType
CastType
Definition: SemaCast.cpp:46
clang::CorrectionCandidateCallback::setTypoName
void setTypoName(IdentifierInfo *II)
Definition: TypoCorrection.h:322
clang::Sema::areLaxCompatibleVectorTypes
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types? That is, given that one of them is a vector,...
Definition: SemaExpr.cpp:8014
clang::Sema::checkVariadicArgument
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
Definition: SemaExpr.cpp:972
diagnoseTautologicalComparison
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:12278
clang::Sema::CreateBuiltinUnaryOp
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15785
clang::Expr::NPC_ValueDependentIsNotNull
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:802
clang::BinaryConditionalOperator
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4215
clang::MSGuidDecl
A global _GUID constant.
Definition: DeclCXX.h:4200
clang::Sema::PDiag
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
clang::ASTContext::getTypeSize
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2274
clang::Sema::NTCUK_Destruct
@ NTCUK_Destruct
Definition: Sema.h:3021
clang::Stmt::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:349
clang::Sema::IncompatibleFunctionPointer
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition: Sema.h:12380
clang::Preprocessor::isMacroDefined
bool isMacroDefined(StringRef Id)
Definition: Preprocessor.h:1329
clang::TNK_Var_template
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
clang::isa
bool isa(CodeGen::Address addr)
Definition: Address.h:212
clang::ParenListExpr::getNumExprs
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5410
clang::CXXDestructorDecl
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2715
clang::Sema::CheckConditionalOperands
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
Definition: SemaExpr.cpp:8838
clang::ImplicitCastExpr::Create
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2063
clang::Sema::GetTypeFromParser
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:3107
clang::OMPIteratorExpr::IteratorDefinition::IteratorDecl
Decl * IteratorDecl
Definition: ExprOpenMP.h:285
DiagnoseConditionalPrecedence
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, Expr *Condition, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseConditionalPrecedence - Emit a warning when a conditional operator and binary operator are mi...
Definition: SemaExpr.cpp:9268
clang::Expr::MLV_ConstQualifiedField
@ MLV_ConstQualifiedField
Definition: Expr.h:301
clang::Sema::getCurLambda
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2346
clang::ValueStmt::getExprStmt
const Expr * getExprStmt() const
Definition: Stmt.cpp:403
clang::Sema::BuildCStyleCastExpr
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
Definition: SemaCast.cpp:3285
clang::AutoType
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5253
clang::DeclRefExpr::getDecl
ValueDecl * getDecl()
Definition: Expr.h:1307
clang::ConstantMatrixType::getNumColumns
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:3612
clang::QualType::hasAddressSpace
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:6764
clang::Type::isFunctionType
bool isFunctionType() const
Definition: Type.h:6892
clang::UnresolvedLookupExpr::Create
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:370
clang::VariableArrayType::getSizeExpr
Expr * getSizeExpr() const
Definition: Type.h:3188
clang::TemplateArgumentLoc
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:484
clang::FunctionProtoType::ExtProtoInfo::ExtInfo
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4107
Type.h
clang::Sema::ActOnOpenMPIteratorVarDecl
void ActOnOpenMPIteratorVarDecl(VarDecl *VD)
Definition: SemaOpenMP.cpp:22461
clang::ImplicitParamDecl
Definition: Decl.h:1657
clang::OpenMPClauseKind
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:27
clang::Sema::AssignmentAction
AssignmentAction
Definition: Sema.h:3707
clang::Expr::isInstantiationDependent
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:216
clang::CXXBasePathElement
Represents an element in a path from a derived class to a base class.
Definition: CXXInheritance.h:44
clang::FunctionDecl::getPointOfInstantiation
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4103
clang::Sema::CheckCXXThisCapture
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
Definition: SemaExprCXX.cpp:1263
clang::Sema::IncompatibleNestedPointerAddressSpaceMismatch
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition: Sema.h:12407
clang::FunctionType::ExtParameterInfo::isNoEscape
bool isNoEscape() const
Definition: Type.h:3747
clang::CR_OpenMP
@ CR_OpenMP
Definition: CapturedStmt.h:19
clang::DeclRefExpr::setDecl
void setDecl(ValueDecl *NewD)
Definition: Expr.cpp:592
clang::VarDecl::hasExternalStorage
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1176
clang::CPlusPlus20
@ CPlusPlus20
Definition: LangStandard.h:57
clang::FieldDecl::hasInClassInitializer
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3083
Expr.h
llvm::SmallString< 32 >
clang::Sema::TooManyArguments
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition: Sema.h:13778
clang::Expr::EvalResult
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:624
clang::Scope::ContinueScope
@ ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition: Scope.h:56
bool
#define bool
Definition: stdbool.h:20
clang::Redeclarable::redecls
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
clang::Sema::ActOnVAArg
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16775
clang::PredefinedExpr::Create
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, IdentKind IK, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:684
clang::TemplateArgumentListInfo::setLAngleLoc
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:609
clang::interp::Cast
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1299
clang::Sema::IsFunctionConversion
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
Definition: SemaOverload.cpp:1628
ASTContext.h
clang::ASTContext::getRecordType
QualType getRecordType(const RecordDecl *Decl) const
Definition: ASTContext.cpp:4804
clang::UnresolvedSet
A set of unresolved declarations.
Definition: UnresolvedSet.h:148
clang::TypeDecl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3273
clang::ASTContext::getIntTypeForBitwidth
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
Definition: ASTContext.cpp:12039
clang::Sema::PerformContextualImplicitConversion
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
Definition: SemaOverload.cpp:6193
clang::CallingConv
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:266
clang::ASTContext::LongAccumTy
CanQualType LongAccumTy
Definition: ASTContext.h:1092
clang::ASTContext::getCommonSugaredType
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
Definition: ASTContext.cpp:13129
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:915
clang::ObjCMethodDecl::getReturnType
QualType getReturnType() const
Definition: DeclObjC.h:331
clang::Sema::InstantiateDefaultArgument
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
Definition: SemaTemplateInstantiateDecl.cpp:4543
clang::FunctionProtoType::getParamTypes
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4241
clang::FunctionTypeLoc::getLocalRangeBegin
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1402
clang::ASTContext::canAssignObjCInterfaces
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
Definition: ASTContext.cpp:9763
clang::ASTContext::FloatTy
CanQualType FloatTy
Definition: ASTContext.h:1090
AnalysisBasedWarnings.h
clang::Type::getPointeeType
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:629
clang::Sema::ArithConvKind
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition: Sema.h:12331
diagnoseAddressOfInvalidType
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:14517
clang::Sema::DefaultFunctionArrayLvalueConversion
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:740
clang::MemberExpr::getMemberLoc
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3361
clang::ObjCIvarDecl::Private
@ Private
Definition: DeclObjC.h:1944
clang::Type::isExtVectorBoolType
bool isExtVectorBoolType() const
Definition: Type.h:7006
clang::StringLiteral
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1779
clang::UnaryOperator::isIncrementDecrementOp
bool isIncrementDecrementOp() const
Definition: Expr.h:2278
clang::Expr::MLV_IncompleteVoidType
@ MLV_IncompleteVoidType
Definition: Expr.h:295
clang::TargetInfo::isTLSSupported
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1456
isInvalid
static bool isInvalid(LocType Loc, bool *Invalid)
Definition: SourceManager.cpp:1232
clang::Scope::ControlScope
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition: Scope.h:63
clang::OverloadCandidateSet::iterator
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1124
checkArithmeticOrEnumeralCompare
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12567
clang::Sema::MaybeBindToTemporary
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
Definition: SemaExprCXX.cpp:7156
clang::dataflow::var
static constexpr Variable var(Literal L)
Returns the variable of L.
Definition: WatchedLiteralsSolver.cpp:71
clang::SourceLocation::isFileID
bool isFileID() const
Definition: SourceLocation.h:102
clang::ASTContext::isPromotableBitField
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
Definition: ASTContext.cpp:7174
clang::ASTContext::getCanonicalType
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2500
clang::CXXRecordDecl::isDerivedFrom
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Definition: CXXInheritance.cpp:67
clang::TypeDecl
Represents a declaration of a type.
Definition: Decl.h:3246
clang::ValueDecl::isWeak
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5040
clang::Type::getAsCXXRecordDecl
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1783
clang::Sema::AA_Passing
@ AA_Passing
Definition: Sema.h:3709
OperationKinds.h
clang::TagDecl::isUnion
bool isUnion() const
Definition: Decl.h:3642
clang::CXXRecordDecl::isStandardLayout
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition: DeclCXX.h:1194
clang::Sema::WarnOnPendingNoDerefs
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
Definition: SemaExpr.cpp:17734
clang::ObjCIvarRefExpr::getLocation
SourceLocation getLocation() const
Definition: ExprObjC.h:589
clang::Sema::isSelfExpr
bool isSelfExpr(Expr *RExpr)
Private Helper predicate to check for 'self'.
Definition: SemaExprObjC.cpp:1916
clang::Sema::BuildObjCStringLiteral
ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S)
Definition: SemaExprObjC.cpp:82
clang::Type::isVariablyModifiedType
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2328
clang::DeclRefExpr::getNameInfo
DeclarationNameInfo getNameInfo() const
Definition: Expr.h:1311
clang::Sema::getLocForEndOfToken
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:57
clang::ParenListExpr::getExpr
Expr * getExpr(unsigned Init)
Definition: Expr.h:5412
clang::SC_Register
@ SC_Register
Definition: Specifiers.h:245
clang::ConstantExpr::getStorageKind
static ResultStorageKind getStorageKind(const APValue &Value)
Definition: Expr.cpp:355
clang::Sema::getCurFPFeatures
FPOptions & getCurFPFeatures()
Definition: Sema.h:1657
clang::Sema::checkTypeSupport
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition: Sema.cpp:1900
clang::SourceManager::isInSystemMacro
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
Definition: SourceManager.h:1519
clang::Type::isAnyComplexType
bool isAnyComplexType() const
Definition: Type.h:6994
clang::Type::isAtomicType
bool isAtomicType() const
Definition: Type.h:7037
clang::ASTContext::getComplexType
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
Definition: ASTContext.cpp:3358
clang::NK_Constant_Narrowing
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:239
clang::FunctionTypeLoc::getLocalRangeEnd
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1410
clang::ASTContext::getConstantMatrixType
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
Definition: ASTContext.cpp:4267
diagnoseUnknownAnyExpr
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:20902
clang::PredefinedExpr::Function
@ Function
Definition: Expr.h:1984
clang::Builtin::Context::hasPtrArgsOrResult
bool hasPtrArgsOrResult(unsigned ID) const
Determines whether this builtin has a result or any arguments which are pointer types.
Definition: Builtins.h:209
ExprObjC.h
clang::ASTContext::getPromotedIntegerType
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
Definition: ASTContext.cpp:7229
clang::NestedNameSpecifierLoc
A C++ nested-name-specifier augmented with source location information.
Definition: NestedNameSpecifier.h:243
clang::Sema::getSelfAssignmentClassMemberCandidate
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
Definition: SemaExpr.cpp:14890
clang::LookupResult::getLookupName
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:243
clang::Sema::CheckShiftOperands
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11957
clang::ObjCIvarRefExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:592
clang::FunctionDecl::getMinRequiredArguments
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3494
clang::Sema::BuildCXXDefaultArgExpr
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5986
NCCK_None
@ NCCK_None
Definition: SemaExpr.cpp:13691
clang::DeclContext::getLookupParent
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1125
clang::Sema::TentativeAnalysisScope
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:9772
clang::Sema::ExpressionEvaluationContextRecord::NumCleanupObjects
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:1289
ExprCXX.h
clang::Sema::isValidSveBitcast
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7929
Base
clang::Type::getAsPlaceholderType
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:7186
clang::Sema::TryImplicitConversion
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
Definition: SemaOverload.cpp:1585
clang::FunctionDecl::getTemplateSpecializationKind
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4026
clang::Sema::CheckCXXBooleanCondition
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
Definition: SemaExprCXX.cpp:4028
clang::DeclContext::isRecord
bool isRecord() const
Definition: DeclBase.h:2008
checkObjCPointerIntrospection
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
Definition: SemaExpr.cpp:14967
clang::Expr::MLV_SubObjCPropertySetting
@ MLV_SubObjCPropertySetting
Definition: Expr.h:306
clang::FunctionDecl::getOverloadedOperator
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3746
clang::CXXDefaultArgExpr
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1247
clang::BinaryOperator::getOpcodeStr
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:2123
clang::FunctionDecl::Create
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2095
IsReadonlyMessage
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:13678
clang::TagDecl::isCompleteDefinition
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3541
clang::OverloadExpr::FindResult::HasFormOfMemberPointer
bool HasFormOfMemberPointer
Definition: ExprCXX.h:3006
clang::Sema::ConditionKind::ConstexprIf
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
clang::RecursiveASTVisitor::VisitStmt
bool VisitStmt(Stmt *S)
Definition: RecursiveASTVisitor.h:366
clang::MatrixType::getElementType
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:3569
clang::Builtin::Context::getName
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
CheckCommaOperands
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:14316
clang::Type::isEnumeralType
bool isEnumeralType() const
Definition: Type.h:6990
clang::DeclRefExpr::hasQualifier
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition: Expr.h:1322
clang::SourceLocExpr::Function
@ Function
Definition: Expr.h:4695
clang::VectorType::GenericVector
@ GenericVector
not a target-specific vector type
Definition: Type.h:3369
clang::BinaryOperator::isBitwiseOp
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:3905
clang::Sema::LK_String
@ LK_String
Definition: Sema.h:3957
clang::QualType::hasQualifiers
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6723
clang::VarDecl::TLS_None
@ TLS_None
Not a TLS variable.
Definition: Decl.h:935
clang::Sema::ResolveExceptionSpec
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
Definition: SemaExceptionSpec.cpp:210
canCaptureVariableByCopy
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
Definition: SemaExpr.cpp:18934
clang::APValue::getAsString
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:936
clang::sema::CapturingScopeInfo::ImpCaptureStyle
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:679
getPrimaryDecl
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:14457
clang::ASTContext::getSignedSizeType
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
Definition: ASTContext.cpp:5983
clang::Sema::InstantiateFunctionDefinition
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
Definition: SemaTemplateInstantiateDecl.cpp:4801
clang::Type::getPointeeOrArrayElementType
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:7367
clang::BlockPointerType
Pointer to a block type.
Definition: Type.h:2856
clang::StandardConversionSequence::Second
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:269
clang::Sema::CheckAltivecInitFromScalar
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
Definition: SemaCast.cpp:2658
clang::OK_MatrixComponent
@ OK_MatrixComponent
A matrix component is a single element of a matrix.
Definition: Specifiers.h:157
clang::TargetInfo::getMaxBitIntWidth
virtual size_t getMaxBitIntWidth() const
Definition: TargetInfo.h:624
clang::Sema::getCurObjCLexicalContext
const DeclContext * getCurObjCLexicalContext() const
Definition: Sema.h:13761
clang::Sema::PerformOpenMPImplicitIntegerConversion
ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op)
Definition: SemaOpenMP.cpp:16325
clang::Sema::LOLR_Template
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition: Sema.h:4377
clang::Type::isObjCQualifiedIdType
bool isObjCQualifiedIdType() const
Definition: Type.h:7045
clang::APValue::isInt
bool isInt() const
Definition: APValue.h:393
clang::ConstantExpr
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1044
PerformCastFn
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1270
clang::Sema::MaybeSuggestAddingStaticToDecl
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:199
isCapturingReferenceToHostVarInCUDADeviceLambda
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
Definition: SemaExpr.cpp:2022
clang::ObjCMessageExpr
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:940
clang::QualType::hasNonTrivialToPrimitiveDestructCUnion
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition: Type.h:6784
clang::LangOptions::ExtendArgsKind::ExtendTo64
@ ExtendTo64
checkVectorResult
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, SourceLocation QuestionLoc)
Return false if the vector condition type and the vector result type are compatible.
Definition: SemaExpr.cpp:8758
clang::QualType::getSingleStepDesugaredType
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1066
clang::Type::getTypeClass
TypeClass getTypeClass() const
Definition: Type.h:1985
SuggestParentheses
static void SuggestParentheses(Sema &Self, SourceLocation Loc, const PartialDiagnostic &Note, SourceRange ParenRange)
SuggestParentheses - Emit a note with a fixit hint that wraps ParenRange in parentheses.
Definition: SemaExpr.cpp:9171
clang::Sema::getOpenCLOptions
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1656
clang::VarDecl::Create
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2079
clang::Sema::ActOnUnaryExprOrTypeTraitExpr
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
Definition: SemaExpr.cpp:4691
clang::OffsetOfNode
Helper class for OffsetOfExpr.
Definition: Expr.h:2352
clang::CXXScopeSpec::getWithLocInContext
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
clang::TypeLocBuilder
Definition: TypeLocBuilder.h:22
clang::Sema::MaybeConvertParenListExprToParenExpr
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
Definition: SemaExpr.cpp:8326
clang::CastExpr::getCastKind
CastKind getCastKind() const
Definition: Expr.h:3527
clang::Decl::isImplicit
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:576
clang::OverloadedOperatorKind
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
clang::Qualifiers::OCL_Autoreleasing
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:180
clang::MemberExpr::getMemberDecl
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
clang::AvailabilitySpec
One specifier in an @available expression.
Definition: Availability.h:30
clang::Sema::CCK_ImplicitConversion
@ CCK_ImplicitConversion
An implicit conversion.
Definition: Sema.h:12203
clang::ASTContext::ShortTy
CanQualType ShortTy
Definition: ASTContext.h:1087
clang::DecayedTypeLoc
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1219
clang::Sema::AA_Returning
@ AA_Returning
Definition: Sema.h:3710
clang::Sema::IncompatiblePointerSign
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:12392
clang::Sema::ConditionResult
Definition: Sema.h:12791
clang::NamedDecl::getFormalLinkage
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.h:398
clang::Sema::PopExpressionEvaluationContext
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17969
clang::Sema::BuildObjCSubscriptExpression
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod)
Build an ObjC subscript pseudo-object expression, given that that's supported by the runtime.
Definition: SemaExprObjC.cpp:764
clang::Expr::NPCK_ZeroExpression
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:778
clang::Type::isUnsignedFixedPointType
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7287
clang::ChooseExpr
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4532
clang::ASTContext::getFunctionNoProtoType
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
Definition: ASTContext.cpp:4383
clang::sema::Capture::isNested
bool isNested() const
Definition: ScopeInfo.h:630
clang::VectorType::getVectorKind
VectorKind getVectorKind() const
Definition: Type.h:3412
clang::ConstraintSatisfaction::IsSatisfied
bool IsSatisfied
Definition: ASTConcept.h:46
clang::DeclRefExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:599
clang::DeclarationName::isDependentName
bool isDependentName() const
Determines whether the name itself is dependent, e.g., because it involves a C++ type that is itself ...
Definition: DeclarationName.cpp:216
clang::sema::BlockScopeInfo::FunctionType
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:765
clang::Sema::LangOpts
const LangOptions & LangOpts
Definition: Sema.h:407
diagnoseUncapturableValueReferenceOrBinding
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
Definition: SemaExpr.cpp:18549
clang::Sema::DefineImplicitMoveConstructor
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
Definition: SemaDeclCXX.cpp:15381
clang::ASTContext::getTargetAddressSpace
unsigned getTargetAddressSpace(LangAS AS) const
Definition: ASTContext.cpp:12311
clang::Sema::LookupIvarInObjCMethod
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
Definition: SemaExpr.cpp:2828
clang::Sema::ActOnSYCLUniqueStableNameExpr
ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, ParsedType ParsedTy)
Definition: SemaExpr.cpp:3590
clang::ASTContext::UnsignedLongLongTy
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1089
clang::ETK_None
@ ETK_None
No keyword precedes the qualified type name.
Definition: Type.h:5587
clang::QualType::getUnqualifiedType
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6728
clang::Type::isObjCLifetimeType
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4441
clang::Sema::ACK_CompAssign
@ ACK_CompAssign
A compound assignment expression.
Definition: Sema.h:12341
clang::ICK_Function_To_Pointer
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:115
clang::Sema::PerformImplicitConversion
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit=false)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType.
Definition: SemaOverload.cpp:1602
clang::Sema::CXXCheckConditionalOperands
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?: under C++ semantics.
Definition: SemaExprCXX.cpp:6480
clang::DeclarationNameInfo::getName
DeclarationName getName() const
getName - Returns the embedded declaration name.
Definition: DeclarationName.h:790
clang::Token::getLength
unsigned getLength() const
Definition: Token.h:129
clang::BlockDecl::Create
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5091
clang::Type::isObjCObjectPointerType
bool isObjCObjectPointerType() const
Definition: Type.h:7024
clang::Sema::ActOnSourceLocExpr
ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:17019
clang::FunctionType::ExtInfo::getCmseNSCall
bool getCmseNSCall() const
Definition: Type.h:3843
clang::Type::isVLSTBuiltinType
bool isVLSTBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2361
clang::FunctionDecl::hasBody
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3038
DiagnoseDirectIsaAccess
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:573
clang::Sema::CorrectTypo
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
Definition: SemaLookup.cpp:5375
clang::Sema::NoteAllOverloadCandidates
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
Definition: SemaOverload.cpp:10643
clang::ASTContext::getWideCharType
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1748
clang::ASTContext::getCorrespondingUnsignedType
QualType getCorrespondingUnsignedType(QualType T) const
Definition: ASTContext.cpp:10993
clang::Type::hasIntegerRepresentation
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:1922
clang::StringLiteral::UTF8
@ UTF8
Definition: Expr.h:1801
ImmediateCallVisitor::VisitBlockDecl
bool VisitBlockDecl(BlockDecl *B)
Definition: SemaExpr.cpp:5955
clang::Sema::ActOnObjCBoolLiteral
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
Definition: SemaExpr.cpp:21118
hasAnyExplicitStorageClass
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:139
CorrectDelayedTyposInBinOp
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15056
clang::ASTContext::adjustStringLiteralBaseType
QualType adjustStringLiteralBaseType(QualType StrLTy) const
Definition: ASTContext.cpp:4634
clang::Sema::UsualUnaryConversions
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition: SemaExpr.cpp:774
clang::CharacterLiteral::Ascii
@ Ascii
Definition: Expr.h:1599
clang::QualType::withCVRQualifiers
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:935
clang::Sema::HandleFunctionTypeMismatch
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
Definition: SemaOverload.cpp:2968
clang::FullExpr::getSubExpr
const Expr * getSubExpr() const
Definition: Expr.h:1029
DiagnosticSema.h
clang::ASTContext::UnsignedCharTy
CanQualType UnsignedCharTy
Definition: ASTContext.h:1088
clang::OpaquePtr< QualType >
clang::DeclarationName::CXXConversionFunctionName
@ CXXConversionFunctionName
Definition: DeclarationName.h:214
clang::CharacterLiteral
Definition: Expr.h:1596
clang::Sema::InstantiateInClassInitializer
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
Definition: SemaTemplateInstantiate.cpp:3381
clang::ASTContext::FractTy
CanQualType FractTy
Definition: ASTContext.h:1094
clang::OverloadCandidateSet
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:951
clang::LangAS
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
ConstMethod
@ ConstMethod
Definition: SemaExpr.cpp:13741
clang::Preprocessor::getSourceManager
SourceManager & getSourceManager() const
Definition: Preprocessor.h:1205
clang::sema::FunctionScopeInfo
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:102
clang::CPlusPlus2b
@ CPlusPlus2b
Definition: LangStandard.h:58
clang::Type::isBlockCompatibleObjCPointerType
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:4351
clang::ASTContext::BuiltinFnTy
CanQualType BuiltinFnTy
Definition: ASTContext.h:1107
clang::VK_LValue
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:127
clang::Expr::IgnoreConversionOperatorSingleStep
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition: Expr.cpp:3045
clang::LangOptions::FEM_UnsetOnCommandLine
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
Definition: LangOptions.h:296
clang::Sema::MarkDeclarationsReferencedInExpr
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt=std::nullopt)
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
Definition: SemaExpr.cpp:20144
clang::Sema::CreateBuiltinMatrixSubscriptExpr
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc)
Definition: SemaExpr.cpp:4979
clang::Sema::diagnoseTypo
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
Definition: SemaLookup.cpp:5672
clang::Sema::tryConvertExprToType
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:4971
clang::Sema::getTemplateInstantiationArgs
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, bool Final=false, const TemplateArgumentList *Innermost=nullptr, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
Definition: SemaTemplateInstantiate.cpp:289
clang::Qualifiers::isAddressSpaceSupersetOf
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:494
clang::Type::isArithmeticType
bool isArithmeticType() const
Definition: Type.cpp:2176
clang::Type::castAs
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7477
clang::OMPIteratorExpr::IteratorDefinition::AssignmentLoc
SourceLocation AssignmentLoc
Definition: ExprOpenMP.h:287
clang::Sema::LookupBinOp
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15587
clang::PredefinedExpr::ComputeName
static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl)
Definition: Expr.cpp:724
clang::ArrayType::getSizeModifier
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3042
clang::Sema::PerformObjectMemberConversion
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Definition: SemaExpr.cpp:3003
clang::Sema::DefineImplicitMoveAssignment
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
Definition: SemaDeclCXX.cpp:14937
clang::CompoundLiteralExpr
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3413
clang::OverloadCandidateSet::BestViableFunction
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
Definition: SemaOverload.cpp:10249
handleIntegerToComplexFloatConversion
static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Converts an integer to complex float type.
Definition: SemaExpr.cpp:1087
clang::Sema::CheckLoopHintExpr
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc)
Definition: SemaExpr.cpp:3720
CheckAlignOfExpr
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4419
clang::Expr::IgnoreParenCasts
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3041
clang::TargetInfo::getTriple
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1190
clang::ASTContext::UnsignedLongTy
CanQualType UnsignedLongTy
Definition: ASTContext.h:1088
OEK_LValue
@ OEK_LValue
Definition: SemaExpr.cpp:13872
clang::ObjCObjectPointerType
Represents a pointer to an Objective C object.
Definition: Type.h:6283
clang::TargetInfo::getSizeType
IntType getSizeType() const
Definition: TargetInfo.h:339
clang::Sema::FinalizeVarWithDestructor
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
Definition: SemaDeclCXX.cpp:15671
clang::Sema::MaybeODRUseExprs
MaybeODRUseExprSet MaybeODRUseExprs
Definition: Sema.h:799
clang::Preprocessor::getSpelling
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
Definition: Preprocessor.h:2053
clang::ParmVarDecl::hasDefaultArg
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:2935
clang::MemberExpr::getBase
Expr * getBase() const
Definition: Expr.h:3249
clang::InitializationSequence::Perform
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:8292
GCCTypeClass::Bool
@ Bool
clang::CallExpr::ADLCallKind
ADLCallKind
Definition: Expr.h:2869
clang::CallExpr::setCallee
void setCallee(Expr *F)
Definition: Expr.h:2965
clang::FunctionProtoType::param_types
ArrayRef< QualType > param_types() const
Definition: Type.h:4388
clang::CXXRecordDecl
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
clang::Sema::ReuseLambdaContextDecl_t
ReuseLambdaContextDecl_t
Definition: Sema.h:5394
clang::Sema::MarkVTableUsed
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
Definition: SemaDeclCXX.cpp:17928
clang::Sema::checkSpecializationVisibility
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
Definition: SemaTemplate.cpp:11493
clang::Sema::ExpressionEvaluationContext
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition: Sema.h:1226
clang::CallExpr::Create
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1478
clang::MemberExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1793
clang::Type::isImageType
bool isImageType() const
Definition: Type.h:7109
clang::Sema::ActOnStmtExprResult
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:16178
clang::Sema::IncompatibleObjCWeakRef
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition: Sema.h:12434
clang::Expr::hasAnyTypeDependentArguments
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3256
clang::getComparisonCategoryForBuiltinCmp
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
Definition: ComparisonCategories.cpp:25
clang::UnaryOperator::getOperatorLoc
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:2226
clang::sema::AnalysisBasedWarnings::Policy
Definition: AnalysisBasedWarnings.h:33
clang::Sema::DiagnoseUnguardedAvailabilityViolations
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
Definition: SemaAvailability.cpp:892
clang::BinaryOperator::Create
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4622
clang::UnqualifiedIdKind::IK_TemplateId
@ IK_TemplateId
A template-id, e.g., f<int>.
clang::TypeLoc::getLocalSourceRange
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:158
clang::OO_None
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
clang::Type::getAsUnionType
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:664
clang::ASTContext::getLogicalOperationType
QualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:1954
clang::tok::TokenKind
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
clang::DeclContext::getRedeclContext
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1829
clang::Sema::computeDeclContext
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
Definition: SemaCXXScopeSpec.cpp:53
castKindToImplicitConversionKind
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:12405
clang::Sema::DefaultedComparisonKind
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:1564
clang::Type::STK_CPointer
@ STK_CPointer
Definition: Type.h:2284
clang::ASTContext::LongLongTy
CanQualType LongLongTy
Definition: ASTContext.h:1087
EnsureImmediateInvocationInDefaultArgs::TransformCXXThisExpr
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
Definition: SemaExpr.cpp:5983
clang::Sema::CheckUnaryExprOrTypeTraitOperand
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:4262
clang::Sema::CTK_ErrorRecovery
@ CTK_ErrorRecovery
Definition: Sema.h:4526
clang::Sema::ActOnUnaryOp
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:16102
clang::Type::isDependentType
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2310
clang::Type::isInstantiationDependentType
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2318
clang::VK_PRValue
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:123
clang::Sema::DiagnoseAssignmentEnum
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr)
DiagnoseAssignmentEnum - Warn if assignment to enum is a constant integer not in the range of enum va...
Definition: SemaStmt.cpp:1628
OpenCLConvertScalarsToVectors
static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType CondTy, SourceLocation QuestionLoc)
Convert scalar operands to a vector that matches the condition in length.
Definition: SemaExpr.cpp:8704
clang::TemplateSpecializationKind
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:176
clang::VectorType::AltiVecVector
@ AltiVecVector
is AltiVec vector
Definition: Type.h:3372
clang::Type::isBuiltinType
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:6982
clang::Sema::DefineImplicitDefaultConstructor
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
Definition: SemaDeclCXX.cpp:13583
clang::QualType::isCanonical
bool isCanonical() const
Definition: Type.h:6692
clang::Sema::Compatible
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:12359
clang::Expr::NPCK_CXX11_nullptr
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition: Expr.h:784
clang::ASTContext::getVectorType
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
Definition: ASTContext.cpp:4118
clang::QualType::isTriviallyCopyableType
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2506
clang::BlockDecl::setIsVariadic
void setIsVariadic(bool value)
Definition: Decl.h:4408
clang::FunctionDecl::getTemplateSpecializationKindForInstantiation
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Determine the kind of template specialization this function represents for the purpose of template in...
Definition: Decl.cpp:4042
clang::CharacterLiteral::UTF16
@ UTF16
Definition: Expr.h:1602
clang::Sema::DefineImplicitCopyAssignment
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
Definition: SemaDeclCXX.cpp:14565
clang::Sema::IntToBlockPointer
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition: Sema.h:12421
clang::Sema::getCurBlock
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2303
clang::Sema::checkPseudoObjectRValue
ExprResult checkPseudoObjectRValue(Expr *E)
Definition: SemaPseudoObject.cpp:1527
clang::Sema::IsDerivedFrom
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
Definition: SemaDeclCXX.cpp:2880
clang::LookupResult::suppressDiagnostics
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:609
clang::LangOptions::FEM_Source
@ FEM_Source
Use the declared type for fp arithmetic.
Definition: LangOptions.h:287
clang::ASTContext::UnsignedIntTy
CanQualType UnsignedIntTy
Definition: ASTContext.h:1088
clang::Type::isMemberPointerType
bool isMemberPointerType() const
Definition: Type.h:6944
clang::VariableArrayType
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3169
clang::Sema::ImpCastExprToType
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:622
clang::sema::CapturingScopeInfo::Captures
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:692
clang::LookupResult::empty
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:339
clang::Sema::PushExpressionEvaluationContext
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17676
clang::FieldDecl::isBitField
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3021
clang::Type::canDecayToPointerType
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:7347
clang::Stmt::getStmtClass
StmtClass getStmtClass() const
Definition: Stmt.h:1177
clang::DeclRefExpr::hasExplicitTemplateArgs
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition: Expr.h:1388
clang::Type::isPointerType
bool isPointerType() const
Definition: Type.h:6896
tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:6776
clang::ASTContext::ObjCQualifiedIdTypesAreCompatible
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
Definition: ASTContext.cpp:9647
tryVectorConvertAndSplat
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, QualType scalarTy, QualType vectorEltTy, QualType vectorTy, unsigned &DiagID)
Try to convert a value of non-vector type to a vector type by converting the type to the element type...
Definition: SemaExpr.cpp:10412
clang::ASTContext::DoubleTy
CanQualType DoubleTy
Definition: ASTContext.h:1090
clang::ObjCRuntime::allowsPointerArithmetic
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
Definition: ObjCRuntime.h:324
clang::OMPIteratorExpr::IteratorRange::Step
Expr * Step
Definition: ExprOpenMP.h:281
clang::PredefinedExpr::IdentKind
IdentKind
Definition: Expr.h:1982
clang::Sema::ActOnFinishFullExpr
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6874
clang::MemberExpr::performsVirtualDispatch
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3390
clang::OMPIteratorHelperData::Upper
Expr * Upper
Normalized upper bound.
Definition: ExprOpenMP.h:240
clang::FunctionCallFilterCCC
Definition: TypoCorrection.h:379
clang::TypeLoc::getAsAdjusted
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2631
false
#define false
Definition: stdbool.h:22
clang::StandardConversionSequence
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:258
DiagnoseBadDivideOrRemainderValues
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:11038
clang::Sema::CheckObjCARCUnavailableWeakConversion
bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType)
Definition: SemaExprObjC.cpp:4578
checkArithmeticIncompletePointerType
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:11210
clang::DeclResult
ActionResult< Decl * > DeclResult
Definition: Ownership.h:268
clang::ConstantExpr::Create
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:403
clang::Sema::PerformCopyInitialization
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10246
clang::ASTContext::getAttributedType
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
Definition: ASTContext.cpp:4846
clang::Sema::isInOpenMPDeclareTargetContext
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition: Sema.h:11277
clang::ActionResult::get
PtrTy get() const
Definition: Ownership.h:169
computeConditionalNullability
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:9304
clang::NamedDecl::getIdentifier
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:268
clang::Sema::MakeFullExpr
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:5004
clang::ValueDecl
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:703
clang::CallExpr::computeDependence
void computeDependence()
Compute and set dependence bits.
Definition: Expr.h:3023
clang::ComplexType
Complex values, per C99 6.2.5p11.
Definition: Type.h:2723
clang::Sema::ExpressionEvaluationContextRecord::ParentCleanup
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:1285
clang::ASTContext::IntTy
CanQualType IntTy
Definition: ASTContext.h:1087
clang::Sema::tryToRecoverWithCall
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
Definition: Sema.cpp:2617
clang::NullabilityKind::Unspecified
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
clang::TargetInfo::getIntMaxTWidth
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:815
clang::Type::isComplexIntegerType
bool isComplexIntegerType() const
Definition: Type.cpp:611
clang::TemplateName
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
clang::BinaryOperator::getLHS
Expr * getLHS() const
Definition: Expr.h:3864
clang::ParenExpr
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2124
clang::UnaryOperator::setSubExpr
void setSubExpr(Expr *E)
Definition: Expr.h:2223
clang::VarDecl::isLocalVarDeclOrParm
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1221
clang::CharUnits::isZero
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
clang::Sema::ActOnCharacterConstant
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3622
clang::Preprocessor::isCodeCompletionEnabled
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
Definition: Preprocessor.h:1945
clang::DeclContext::addDecl
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1607
clang::Sema::BuildObjCNumericLiteral
ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number)
BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the numeric literal expression.
Definition: SemaExprObjC.cpp:317
clang::FunctionProtoType
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4023
clang::ASTContext::Idents
IdentifierTable & Idents
Definition: ASTContext.h:631
clang::Sema::CheckShadowingDeclModification
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
Definition: SemaDecl.cpp:8314
clang::ASTContext::Int128Ty
CanQualType Int128Ty
Definition: ASTContext.h:1087
clang::ASTContext::LongFractTy
CanQualType LongFractTy
Definition: ASTContext.h:1094
clang::TemplateArgumentListInfo::size
unsigned size() const
Definition: TemplateBase.h:612
clang::CharSourceRange::getTokenRange
static CharSourceRange getTokenRange(SourceRange R)
Definition: SourceLocation.h:261
clang::CallExpr::getNumArgs
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2991
clang::Sema::CheckEnableIf
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
Definition: SemaOverload.cpp:6824
clang::Sema::CompatiblePointerDiscardsQualifiers
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:12396
clang::DeclContext::getParent
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1929
clang::Expr::getExprLoc
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:330
clang::RecordDecl::fields
field_range fields() const
Definition: Decl.h:4223
clang::OMPArrayShapingExpr::Create
static OMPArrayShapingExpr * Create(const ASTContext &Context, QualType T, Expr *Op, SourceLocation L, SourceLocation R, ArrayRef< Expr * > Dims, ArrayRef< SourceRange > BracketRanges)
Definition: Expr.cpp:4958
clang::TypeLoc::getAs
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:88
clang::ConstantExpr::isImmediateInvocation
bool isImmediateInvocation() const
Definition: Expr.h:1122
clang::NOUR_None
@ NOUR_None
This is an odr-use.
Definition: Specifiers.h:163
clang::ElaboratedTypeLoc::setElaboratedKeywordLoc
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2270
clang::TemplateDecl
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:407
clang::DeclarationName::isIdentifier
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Definition: DeclarationName.h:384
clang::Sema::CheckPointerToMemberOperands
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
Definition: SemaExprCXX.cpp:5942
clang::C2x
@ C2x
Definition: LangStandard.h:52
clang::Type::isSizelessBuiltinType
bool isSizelessBuiltinType() const
Definition: Type.cpp:2329
clang::LangOptions::LaxVectorConversionKind::All
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
clang::QualType::isNull
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:803
clang::Type::isBFloat16Type
bool isBFloat16Type() const
Definition: Type.h:7217
Begin
SourceLocation Begin
Definition: USRLocFinder.cpp:165
clang::Scope::getFlags
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:241
clang::BlockExpr
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5815
clang::StmtExpr
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4357
llvm::ArrayRef
Definition: LLVM.h:31
clang::Sema::ACK_Conditional
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:12339
CheckIdentityFieldAssignment
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:14067
Value
Value
Definition: UninitializedValues.cpp:102
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
clang::Builtin::Context::isInStdNamespace
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:182
clang::ICK_Floating_Integral
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
clang::Sema::AA_Passing_CFAudited
@ AA_Passing_CFAudited
Definition: Sema.h:3715
clang::ValueDecl::getPotentiallyDecomposedVarDecl
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3252
clang::Type::isClkEventT
bool isClkEventT() const
Definition: Type.h:7097
clang::Sema::PopFunctionScopeInfo
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2234
Scope.h
clang::Sema::ProcessDeclAttributes
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
Definition: SemaDeclAttr.cpp:9601
clang::EnterExpressionEvaluationContext
RAII object that enters a new expression evaluation context.
Definition: Sema.h:13916
clang::Sema::ActOnStartStmtExpr
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:16122
clang::TypeLoc
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:58
clang::Expr::IgnoreParenImpCasts
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3036
clang::ASTContext::LongTy
CanQualType LongTy
Definition: ASTContext.h:1087
clang::BinaryOperator::isComparisonOp
bool isComparisonOp() const
Definition: Expr.h:3915
clang::Sema::CreateOverloadedUnaryOp
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
Definition: SemaOverload.cpp:13556
clang::AddrLabelExpr
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:4312
clang::ObjCPropertyDecl
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:729
clang::Sema::CheckSizelessVectorOperands
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
Definition: SemaExpr.cpp:10876
clang::ConversionFixItGenerator::Kind
OverloadFixItKind Kind
The type of fix applied.
Definition: SemaFixItUtils.h:49
clang::CanQual::withConst
QualType withConst() const
Retrieves a version of this type with const applied.
Definition: CanonicalType.h:161
clang::InitializedEntity::setParameterCFAudited
void setParameterCFAudited()
Definition: Initialization.h:549
hasIsEqualMethod
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:12084
clang::ObjCMethodDecl::isInstanceMethod
bool isInstanceMethod() const
Definition: DeclObjC.h:428
clang::Sema::MarkCaptureUsedInEnclosingContext
void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
Definition: SemaExpr.cpp:18543
clang::FloatingLiteral::Create
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1084
clang::Type::isQueueT
bool isQueueT() const
Definition: Type.h:7101
clang::Sema::VerifyICEDiagnoser::Suppress
bool Suppress
Definition: Sema.h:12894
clang::TargetInfo::CharPtrBuiltinVaList
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:289
clang::Sema::Consumer
ASTConsumer & Consumer
Definition: Sema.h:410
clang::ConstantExpr::MoveIntoResult
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition: Expr.cpp:430
clang::ArraySubscriptExpr
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2657
clang::Sema::DefaultLvalueConversion
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:630
clang::CharSourceRange
Represents a character-granular source range.
Definition: SourceLocation.h:253
clang::Type::isFixedPointOrIntegerType
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition: Type.h:7257
DiagnoseLogicalAndInLogicalOrLHS
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
Definition: SemaExpr.cpp:15446
clang::Type::STK_Floating
@ STK_Floating
Definition: Type.h:2290
clang::RISCV::Float
@ Float
Definition: RISCVVIntrinsicUtils.h:212
ASTMutationListener.h
clang::DeclContext::getOuterLexicalRecordContext
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1855
clang::Sema
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:358
clang::ObjCInterfaceDecl::hasDefinition
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1516
clang::DefaultFilterCCC
Definition: TypoCorrection.h:352
clang::ActionResult::isInvalid
bool isInvalid() const
Definition: Ownership.h:165
DiagnoseConstAssignment
static void DiagnoseConstAssignment(Sema &S, const Expr *E, SourceLocation Loc)
Emit the "read-only variable not assignable" error and print notes to give more information about why...
Definition: SemaExpr.cpp:13750
isObjCPointer
static bool isObjCPointer(const MemRegion *R)
Definition: BugReporterVisitors.cpp:1269
clang::QualType::isPODType
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2398
clang::Sema::CheckExtraCXXDefaultArguments
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
Definition: SemaDeclCXX.cpp:407
clang::VarDecl::getTemplateSpecializationKind
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2675
checkCondition
static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:8390
clang::LangOptions::AltivecSrcCompatKind::XL
@ XL
clang::Qualifiers::addConst
void addConst()
Definition: Type.h:266
clang::Sema::ActOnConditionalOp
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:9358
clang::ASTContext::CharTy
CanQualType CharTy
Definition: ASTContext.h:1080
clang::Sema::resolveAndFixAddressOfSingleOverloadCandidate
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
Definition: SemaOverload.cpp:12725
clang::ObjCRuntime::allowsSizeofAlignof
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
Definition: ObjCRuntime.h:316
clang::BinaryOperator::getOperatorLoc
SourceLocation getOperatorLoc() const
Definition: Expr.h:3856
clang::Expr::MLV_InvalidMessageExpression
@ MLV_InvalidMessageExpression
Definition: Expr.h:307
clang::sema::PossiblyUnreachableDiag
Definition: ScopeInfo.h:89
clang::Sema::TransformToPotentiallyEvaluated
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17655
State
LineState State
Definition: UnwrappedLineFormatter.cpp:1147
clang::UnaryOperatorKind
UnaryOperatorKind
Definition: OperationKinds.h:30
clang::CorrectionCandidateCallback::IsAddressOfOperand
bool IsAddressOfOperand
Definition: TypoCorrection.h:337
clang::Sema::CheckSubtractionOperands
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11523
clang::ASTContext::HalfTy
CanQualType HalfTy
Definition: ASTContext.h:1102
llvm::SaveAndRestore
Definition: LLVM.h:40
diagnoseArithmeticOnVoidPointer
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:11138
clang::Declarator::isInvalidType
bool isInvalidType() const
Definition: DeclSpec.h:2627
clang::FunctionProtoType::getNumParams
unsigned getNumParams() const
Definition: Type.h:4234
clang::Sema::OMPIteratorData
Data structure for iterator expression.
Definition: Sema.h:5752
clang::Sema::checkUnusedDeclAttributes
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration,...
Definition: SemaDeclAttr.cpp:9492
clang::ObjCInterfaceDecl::getSuperClass
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:351
clang::Type::isPipeType
bool isPipeType() const
Definition: Type.h:7116
clang::Sema::ActOnOpenMPCall
ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig)
Given the potential call expression Call, determine if there is a specialization via the OpenMP decla...
Definition: SemaOpenMP.cpp:7248
clang::Sema::AddOverloadCandidate
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={})
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
Definition: SemaOverload.cpp:6423
handleFixedPointConversion
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
Definition: SemaExpr.cpp:1431
clang::DeclaratorDecl::setQualifierInfo
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1928
clang::Sema::isOpenMPPrivateDecl
OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const
Check if the specified variable is used in 'private' clause.
Definition: SemaOpenMP.cpp:2504
clang::ImplicitConversionKind
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition: Overload.h:104
clang::Sema::VerifyICEDiagnoser::diagnoseFold
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:17462
ASTConsumer.h
clang::Sema::AA_Initializing
@ AA_Initializing
Definition: Sema.h:3712
clang::OverloadExpr
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2954
clang::Sema::checkAddressOfFunctionIsAvailable
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
Definition: SemaOverload.cpp:10536
diagnoseUseOfInternalDeclInInlineFunction
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, const NamedDecl *D, SourceLocation Loc)
Check whether we're in an extern inline function and referring to a variable or function with interna...
Definition: SemaExpr.cpp:155
clang::Expr::LV_MemberFunction
@ LV_MemberFunction
Definition: Expr.h:284
clang::ASTContext::Char32Ty
CanQualType Char32Ty
Definition: ASTContext.h:1086
clang::Sema::isConstantEvaluated
bool isConstantEvaluated()
Definition: Sema.h:1050
DiagnoseRecursiveConstFields
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:13875
clang::Type::STK_MemberPointer
@ STK_MemberPointer
Definition: Type.h:2287
clang::DeclContext::Encloses
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1244
clang::LookupResult::getResultKind
LookupResultKind getResultKind() const
Definition: Lookup.h:321
clang::NamedDecl::getQualifiedNameAsString
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1629
clang::Sema::PushOnScopeChains
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1537
clang::Sema::BuildQualifiedDeclarationNameExpr
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
Definition: SemaExpr.cpp:2737
clang::NumericLiteralParser
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber,...
Definition: LiteralSupport.h:42
clang::Builtin::Context::isDirectlyAddressable
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:188
clang::OK_VectorComponent
@ OK_VectorComponent
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:145
clang::Sema::CFT_Device
@ CFT_Device
Definition: Sema.h:13049
clang::Redeclarable::getMostRecentDecl
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
clang::CC_X86VectorCall
@ CC_X86VectorCall
Definition: Specifiers.h:271
clang::sema::LambdaScopeInfo::IntroducerRange
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:842
clang::Type::isOverloadableType
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:7333
clang::Sema::ActOnNumericConstant
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3748
clang::Sema::CheckVectorOperands
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
Definition: SemaExpr.cpp:10656
clang::BinaryOperatorKind
BinaryOperatorKind
Definition: OperationKinds.h:25
clang::ASTContext::getTypeSizeInCharsIfKnown
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
Definition: ASTContext.h:2293
clang::Sema::LookupSingleName
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
Definition: SemaLookup.cpp:3289
clang::NOUR_Unevaluated
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:165
clang::VarDecl::getInit
const Expr * getInit() const
Definition: Decl.h:1327
clang::FunctionType::ExtInfo
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3793
clang::Sema::getCurFunctionAvailabilityContext
sema::FunctionScopeInfo * getCurFunctionAvailabilityContext()
Retrieve the current function, if any, that should be analyzed for potential availability violations.
Definition: SemaAvailability.cpp:917
clang::Sema::getCurMethodDecl
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1462
CheckObjCTraitOperandConstraints
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4221
clang::Type::isPlaceholderType
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:7180
clang::ExprValueKind
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:120
clang::Sema::LK_Boxed
@ LK_Boxed
Definition: Sema.h:3956
clang::ArrayType::Static
@ Static
Definition: Type.h:3026
clang::Expr::isValueDependent
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:170
clang::Sema::getExprRange
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:497
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:85
clang::Sema::DefaultVariadicArgumentPromotion
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but will create a trap if the resul...
Definition: SemaExpr.cpp:1019
CheckCompleteParameterTypesForMangler
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:18122
clang::Sema::NTCUC_FunctionReturn
@ NTCUC_FunctionReturn
Definition: Sema.h:2995
clang::Sema::CreateOverloadedBinOp
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
Definition: SemaOverload.cpp:13818
clang::Sema::CheckAssignmentConstraints
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9720
clang::Sema::getFunctionLevelDeclContext
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false)
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1437
clang::TypedefDecl
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3390
clang::Token::getLocation
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:126
clang::Type::getAsComplexIntegerType
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:622
ConstructTransparentUnion
static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult, QualType UnionType, FieldDecl *Field)
Constructs a transparent union from an expression that is used to initialize the transparent union.
Definition: SemaExpr.cpp:10100
clang::Expr::EvaluateAsRValue
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Definition: ExprConstant.cpp:15211
clang::Expr::EvaluateAsInt
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
Definition: ExprConstant.cpp:15231
clang::ASTContext::getTargetInfo
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:744
recoverFromMSUnqualifiedLookup
static Expr * recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, DeclarationNameInfo &NameInfo, SourceLocation TemplateKWLoc, const TemplateArgumentListInfo *TemplateArgs)
In Microsoft mode, if we are inside a template class whose parent class has dependent base classes,...
Definition: SemaExpr.cpp:2444
clang::VectorType::AltiVecBool
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition: Type.h:3378
diagnoseStringPlusChar
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Emit a warning when adding a char literal to a string.
Definition: SemaExpr.cpp:11347
clang::Type::isObjCQualifiedClassType
bool isObjCQualifiedClassType() const
Definition: Type.h:7051
clang::Sema::checkUnknownAnyArg
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that's being passed to an __unknown_anytype parameter.
Definition: SemaExpr.cpp:20879
clang::TypoCorrection::getCorrectionAsIdentifierInfo
IdentifierInfo * getCorrectionAsIdentifierInfo() const
Definition: TypoCorrection.h:86
clang::sema::FunctionScopeInfo::markSafeWeakUse
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Definition: ScopeInfo.cpp:159
checkConditionalPointerCompatibility
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:8423
EnsureImmediateInvocationInDefaultArgs
Definition: SemaExpr.cpp:5968
clang::Expr::isNullPointerConstant
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3863
clang::BinaryOperator::getOverloadedOpcode
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2132
captureInLambda
static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, const Sema::TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the lambda.
Definition: SemaExpr.cpp:18829
clang::LangOptions::isSubscriptPointerArithmetic
bool isSubscriptPointerArithmetic() const
Definition: LangOptions.h:537
clang::Sema::AA_Converting
@ AA_Converting
Definition: Sema.h:3711
BuildFloatingLiteral
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3688
clang::Sema::MarkDeclRefReferenced
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:19980
clang::ASTContext::CUDAExternalDeviceDeclODRUsedByHost
llvm::DenseSet< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
Definition: ASTContext.h:1147
clang::SourceLocation::isMacroID
bool isMacroID() const
Definition: SourceLocation.h:103
clang::sema::BlockScopeInfo::TheScope
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition: ScopeInfo.h:761
clang::sema::CapturingScopeInfo::CaptureMap
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition: ScopeInfo.h:685
clang::Sema::ActOnOMPIteratorExpr
ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc, ArrayRef< OMPIteratorData > Data)
Definition: SemaExpr.cpp:5354
clang::Sema::getTemplateDepth
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
Definition: SemaTemplate.cpp:54
clang::PartialDiagnostic
Definition: PartialDiagnostic.h:31
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:82
clang::Sema::tryCaptureOpenMPLambdas
void tryCaptureOpenMPLambdas(ValueDecl *V)
Function tries to capture lambda's captured variables in the OpenMP region before the original lambda...
Definition: SemaOpenMP.cpp:4721
clang::FunctionDecl::isExternC
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3307
clang::Type::isBooleanType
bool isBooleanType() const
Definition: Type.h:7320
clang::ASTContext::getCorrespondingSignedType
QualType getCorrespondingSignedType(QualType T) const
Definition: ASTContext.cpp:11067
clang::Type::getScalarTypeKind
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2192
clang::Sema::InvalidOperands
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
Definition: SemaExpr.cpp:10349
clang::Sema::isValidVarArgType
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:922
clang::Sema::CreateUnaryExprOrTypeTraitExpr
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4598
clang::ASTContext::getLValueReferenceType
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
Definition: ASTContext.cpp:3510
diagnoseArithmeticOnNullPointer
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:11151
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
clang::Sema::MaybeCreateExprWithCleanups
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
Definition: SemaExprCXX.cpp:7327
clang::Sema::SemaDiagnosticBuilder
A generic diagnostic builder for errors which may or may not be deferred.
Definition: Sema.h:1770
clang::Sema::ObjCLiteralKind
ObjCLiteralKind
Definition: Sema.h:3952
clang::DeclContext::getInnermostBlockDecl
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1141
clang::BuiltinType::getKind
Kind getKind() const
Definition: Type.h:2662
clang::InitializationKind
Describes the kind of initialization being performed, along with location information for tokens rela...
Definition: Initialization.h:566
clang::Sema::BuildAsTypeExpr
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
Definition: SemaExpr.cpp:7121
diagnoseXorMisusedAsPow
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:13267
clang::ActionResult< Expr * >
clang::Type::isObjCObjectType
bool isObjCObjectType() const
Definition: Type.h:7028
clang::ASTContext::isObjCNSObjectType
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2254
clang::ArrayTypeLoc
Wrapper for source info for arrays.
Definition: TypeLoc.h:1516
DiagnoseBadShiftValues
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
Definition: SemaExpr.cpp:11669
clang::LangOptions::LaxVectorConversionKind::None
@ None
Permit no implicit vector bitcasts.
clang::Sema::Cleanup
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:786
getUDSuffixLoc
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
Definition: SemaExpr.cpp:1814
clang::Sema::getPreprocessor
Preprocessor & getPreprocessor() const
Definition: Sema.h:1661
clang::VarDecl::isUsableInConstantExpressions
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2429
isPotentiallyConstantEvaluatedContext
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:18057
clang::MangleNumberingContext
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
Definition: MangleNumberingContext.h:29
clang::ElaboratedTypeLoc
Definition: TypeLoc.h:2261
clang::InitializationKind::CreateDirectList
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Definition: Initialization.h:634
clang::Token::setLocation
void setLocation(SourceLocation L)
Definition: Token.h:134
clang::Sema::MarkFunctionParmPackReferenced
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
Definition: SemaExpr.cpp:20021
clang::LangOptions::AltivecSrcCompatKind::Mixed
@ Mixed
clang::Sema::ActOnConstantExpression
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19684
clang::CXXThisExpr
Represents the this expression in C++.
Definition: ExprCXX.h:1148
clang::TemplateArgument::getAsDecl
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:294
clang::Sema::ExpressionEvaluationContext::ConstantEvaluated
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
checkArithmeticNull
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:10954
clang::isPtrSizeAddressSpace
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:88
clang::ExtVectorElementExpr
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:5755
clang::Sema::ActOnConvertVectorExpr
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_convertvector(...)
Definition: SemaExpr.cpp:7140
clang::Sema::targetDiag
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1861
clang::FunctionTypeLoc::getParam
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1464
clang::Sema::tryCaptureVariable
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
Definition: SemaExpr.cpp:19036
clang::sema::LambdaScopeInfo
Definition: ScopeInfo.h:832
clang::ObjCMethodDecl
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:138
clang::Sema::isImmediateFunctionContext
bool isImmediateFunctionContext() const
Definition: Sema.h:9682
clang::OK_ObjCProperty
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:149
clang::TypoExpr
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:6212
clang::PointerType
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2776
clang::ASTContext::areComparableObjCPointerTypes
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
Definition: ASTContext.cpp:10191
diagnoseArithmeticOnTwoFunctionPointers
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:11180
clang::Sema::MaybeODRUseExprSet
llvm::SetVector< Expr *, SmallVector< Expr *, 4 >, llvm::SmallPtrSet< Expr *, 4 > > MaybeODRUseExprSet
Store a set of either DeclRefExprs or MemberExprs that contain a reference to a variable (constant) t...
Definition: Sema.h:798
clang::Sema::CheckParmsForFunctionDef
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
Helpers for dealing with blocks and functions.
Definition: SemaChecking.cpp:15822
ScopeInfo.h
clang::CleanupInfo::mergeFrom
void mergeFrom(CleanupInfo Rhs)
Definition: CleanupInfo.h:38
clang::NullabilityKind
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:320
clang::ASTContext::getBuiltinVaListType
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2073
clang::Sema::LookupInObjCMethod
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
Definition: SemaExpr.cpp:2965
clang::LangAS::Default
@ Default
clang::LookupResult::getNamingClass
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:429
CheckDeclInExpr
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, bool AcceptInvalid)
Diagnoses obvious problems with the use of the given declaration as an expression.
Definition: SemaExpr.cpp:3193
handleIntToFloatConversion
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
Definition: SemaExpr.cpp:1164
clang::RecoveryExpr::Create
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition: Expr.cpp:4918
clang::Type::isHalfType
bool isHalfType() const
Definition: Type.h:7208
clang::EnumType::getDecl
EnumDecl * getDecl() const
Definition: Type.h:4856
clang::ASTContext::OMPArrayShapingTy
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1117
DoMarkVarDeclReferenced
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19754
clang::CanQual::getUnqualifiedType
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Definition: CanonicalType.h:619
clang::sema::CapturingScopeInfo::ImpCap_LambdaByref
@ ImpCap_LambdaByref
Definition: ScopeInfo.h:675
clang::StmtResult
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:263
clang::Type::hasUnsignedIntegerRepresentation
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2132
clang::Sema::OutermostDeclarationWithDelayedImmediateInvocations
std::optional< ExpressionEvaluationContextRecord::InitializationContext > OutermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:9713
clang::Sema::getCurScope
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:13746
clang::Expr::HasSideEffects
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3504
clang::Sema::CheckUnusedVolatileAssignment
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
Definition: SemaExpr.cpp:17754
DoMarkBindingDeclReferenced
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
Definition: SemaExpr.cpp:19908
clang::CXXOperatorCallExpr::getSourceRange
SourceRange getSourceRange() const
Definition: ExprCXX.h:161
clang::Expr::NullPointerConstantKind
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:769
clang::Sema::DefineImplicitLambdaToBlockPointerConversion
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
Definition: SemaDeclCXX.cpp:15494
clang::Sema::CheckSingleAssignmentConstraints
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:10171
clang::ASTContext::getAddrSpaceQualType
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
Definition: ASTContext.cpp:3139
clang::Sema::AA_Casting
@ AA_Casting
Definition: Sema.h:3714
ConstMember
@ ConstMember
Definition: SemaExpr.cpp:13740
clang::Builtin::ID
ID
Definition: Builtins.h:64
clang::Sema::UnparsedDefaultArgLocs
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:1490
clang::FunctionProtoType::ExtProtoInfo
Extra information about a function prototype.
Definition: Type.h:4106
clang::CXXBasePath
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
Definition: CXXInheritance.h:70
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:111
clang::LangOptions::FEM_Double
@ FEM_Double
Use the type double for fp arithmetic.
Definition: LangOptions.h:289
OriginalExprKind
OriginalExprKind
Definition: SemaExpr.cpp:13869
clang::Expr::setType
void setType(QualType t)
Definition: Expr.h:144
clang::UnresolvedMemberExpr::getNamingClass
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition: ExprCXX.cpp:1597
clang::TargetInfo::getTypeWidth
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:266
clang::UnaryOperator::getSubExpr
Expr * getSubExpr() const
Definition: Expr.h:2222
clang::FieldDecl::getParent
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3135
clang::OMPArraySectionExpr
OpenMP 5.0 [2.1.5, Array Sections].
Definition: ExprOpenMP.h:56
clang::Expr::IgnoreParens
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3032
PartialDiagnostic.h
checkThreeWayNarrowingConversion
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:12442
clang::AR_Unavailable
@ AR_Unavailable
Definition: DeclBase.h:73
clang::Sema::CheckLogicalOperands
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13575
clang::Sema::mergeDeclAttributes
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3168
RecordModifiableNonNullParam
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:14748
clang::StandardConversionSequence::getNarrowingKind
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
Definition: SemaOverload.cpp:314
clang
Definition: CalledOnceCheck.h:17
clang::Type::isAnyPointerType
bool isAnyPointerType() const
Definition: Type.h:6900
clang::Sema::CFT_Global
@ CFT_Global
Definition: Sema.h:13050
clang::TemplateArgumentListInfo::setRAngleLoc
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:610
clang::Sema::CreateRecoveryExpr
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21171
clang::IndirectFieldDecl
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3197
clang::DeclContext::lookup
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1693
clang::ObjCIvarRefExpr::isArrow
bool isArrow() const
Definition: ExprObjC.h:584
clang::ICK_Complex_Real
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:169
clang::Sema::DiagIfReachable
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
Definition: SemaExpr.cpp:20155
clang::VectorType::getElementType
QualType getElementType() const
Definition: Type.h:3406
hlsl::int64_t
long int64_t
Definition: hlsl_basic_types.h:26
clang::FunctionProtoType::ExtProtoInfo::HasTrailingReturn
bool HasTrailingReturn
Definition: Type.h:4109
clang::Expr::LV_ArrayTemporary
@ LV_ArrayTemporary
Definition: Expr.h:287
clang::Expr::LV_IncompleteVoidType
@ LV_IncompleteVoidType
Definition: Expr.h:280
clang::VarDecl::DeclarationOnly
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1254
clang::Selector
Smart pointer class that efficiently represents Objective-C method names.
Definition: IdentifierTable.h:759
clang::Type::isArrayType
bool isArrayType() const
Definition: Type.h:6962
SemaFixItUtils.h
clang::sema::CapturedRegionScopeInfo::OpenMPCaptureLevel
unsigned short OpenMPCaptureLevel
Definition: ScopeInfo.h:799
clang::interp::InitField
bool InitField(InterpState &S, CodePtr OpPC, uint32_t I)
1) Pops the value from the stack 2) Peeks a pointer from the stack 3) Pushes the value to field I of ...
Definition: Interp.h:882
clang::Type::isIntegralOrUnscopedEnumerationType
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1967
clang::Sema::LK_Array
@ LK_Array
Definition: Sema.h:3953
clang::StringLiteral::StringKind
StringKind
StringLiteral is followed by several trailing objects.
Definition: Expr.h:1801
RecursiveASTVisitor.h
EnsureImmediateInvocationInDefaultArgs::TransformBlockExpr
ExprResult TransformBlockExpr(BlockExpr *E)
Definition: SemaExpr.cpp:5978
clang::NestedNameSpecifier::getAsType
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
Definition: NestedNameSpecifier.h:196
clang::CharacterLiteral::UTF32
@ UTF32
Definition: Expr.h:1603
clang::Sema::areSameVectorElemTypes
bool areSameVectorElemTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7993
checkDirectCallValidity
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:6707
clang::Sema::VerifyICEDiagnoser
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:12892
clang::Qualifiers::getObjCLifetime
ObjCLifetime getObjCLifetime() const
Definition: Type.h:351
clang::ASTContext::getObjCClassRedefinitionType
QualType getObjCClassRedefinitionType() const
Retrieve the type that Class has been defined to, which may be different from the built-in Class if C...
Definition: ASTContext.h:1832
clang::DeclaratorContext::Block
@ Block
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:72
clang::ObjCIvarDecl
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1939
clang::QualType::withConst
QualType withConst() const
Definition: Type.h:915
clang::Sema::getScopeForContext
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2098
clang::Sema::Incompatible
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:12438
clang::UnaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:2217
clang::BinaryOperator::getRHS
Expr * getRHS() const
Definition: Expr.h:3866
clang::ASTContext::isSentinelNullExpr
bool isSentinelNullExpr(const Expr *E)
Definition: ASTContext.cpp:2965
clang::Expr::MLV_ConstAddrSpace
@ MLV_ConstAddrSpace
Definition: Expr.h:302
clang::Preprocessor::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:1198
DiagnosedUnqualifiedCallsToStdFunctions
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call)
Definition: SemaExpr.cpp:6817
std::arg
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:40
clang::CXXRecordDecl::getCanonicalDecl
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:507
clang::Sema::isOpenMPCapturedByRef
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const
Return true if the provided declaration VD should be captured by reference.
Definition: SemaOpenMP.cpp:2107
clang::ParmVarDecl::hasUninstantiatedDefaultArg
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1845
clang::Declarator
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1834
clang::ASTContext::getCorrespondingSaturatedType
QualType getCorrespondingSaturatedType(QualType Ty) const
Definition: ASTContext.cpp:13192
clang::DeclaratorContext::Condition
@ Condition
clang::OverloadExpr::FindResult::Expression
OverloadExpr * Expression
Definition: ExprCXX.h:3004
clang::FunctionProtoType::isParamConsumed
bool isParamConsumed(unsigned I) const
Definition: Type.h:4450
clang::Sema::ExpressionEvaluationContextRecord
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:1280
clang::Sema::VerifyICEDiagnoser::diagnoseNotICE
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
clang::ObjCIsaExpr
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition: ExprObjC.h:1481
clang::Expr::isIntegerConstantExpr
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Definition: ExprConstant.cpp:16000
ConvertUTF8ToWideString
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3518
clang::ASTContext::getFixedPointSemantics
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
Definition: ASTContext.cpp:13334
clang::Sema::BuildVAArgExpr
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16782
DiagnoseCalleeStaticArrayParam
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:6470
clang::ConversionFixItGenerator::isNull
bool isNull()
Definition: SemaFixItUtils.h:84
clang::Sema::CanUseDecl
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:66
clang::ASTContext::hasCvrSimilarType
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
Definition: ASTContext.cpp:6222
clang::ObjCProtocolDecl
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2068
clang::ElaboratedTypeLoc::setQualifierLoc
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2284
clang::Sema::isCompleteType
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:2478
clang::ParenListExpr::getRParenLoc
SourceLocation getRParenLoc() const
Definition: Expr.h:5428
clang::CastExpr::setSubExpr
void setSubExpr(Expr *E)
Definition: Expr.h:3535
clang::Sema::RequireCompleteSizedType
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &... Args)
Definition: Sema.h:2503
clang::Expr::getType
QualType getType() const
Definition: Expr.h:143
clang::CXXScopeSpec::getScopeRep
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:78
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:110
IsTypeModifiable
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:13728
clang::CorrectionCandidateCallback
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
Definition: TypoCorrection.h:281
NCCK_Lambda
@ NCCK_Lambda
Definition: SemaExpr.cpp:13691
clang::DeclaratorContext::FunctionalCast
@ FunctionalCast
CheckRealImagOperand
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4708
clang::ICK_Floating_Conversion
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:136
clang::NullabilityKind::NullableResult
@ NullableResult
clang::Attr
Attr - This represents one attribute.
Definition: Attr.h:40
clang::NK_Variable_Narrowing
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:243
clang::TypeSourceInfo
A container of type source information.
Definition: Type.h:6606
clang::Sema::ActOnIntegerConstant
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3682
clang::FunctionType::getReturnType
QualType getReturnType() const
Definition: Type.h:3947
clang::BinaryOperator::getOverloadedOperator
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2170
clang::NamedDecl::getDeclName
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:313
clang::FixItHint::CreateRemoval
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
ImmediateCallVisitor
Definition: SemaExpr.cpp:5923
clang::CompoundAssignOperator::Create
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition: Expr.cpp:4644
clang::sema::CapturingScopeInfo::HasImplicitReturnType
bool HasImplicitReturnType
Definition: ScopeInfo.h:696
needsConversionOfHalfVec
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, Expr *E0, Expr *E1=nullptr)
Returns true if conversion between vectors of halfs and vectors of floats is needed.
Definition: SemaExpr.cpp:15079
clang::TargetInfo::getPlatformName
StringRef getPlatformName() const
Retrieve the name of the platform as it is used in the availability attribute.
Definition: TargetInfo.h:1534
clang::DeclContext::isDependentContext
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1174
clang::Preprocessor::getLocForEndOfToken
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
Definition: Preprocessor.h:2162
clang::Token::setKind
void setKind(tok::TokenKind K)
Definition: Token.h:94
clang::LookupResult::getLookupKind
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:253
clang::Sema::ActOnParenExpr
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4164
clang::ObjCMessageExpr::getMethodDecl
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1346
clang::Sema::ExpressionEvaluationContextRecord::VolatileAssignmentLHSs
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:1319
unsigned
warnOnSizeofOnArrayDecay
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
Definition: SemaExpr.cpp:4239
clang::Sema::IgnoredValueConversions
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression's result is syntactically ignored,...
Definition: SemaExprCXX.cpp:8144
clang::Sema::DiagnoseCommaOperator
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Definition: SemaExpr.cpp:14267
clang::BinaryOperator::isBitwiseOp
bool isBitwiseOp() const
Definition: Expr.h:3906
clang::Sema::ExpressionEvaluationContextRecord::isConstantEvaluated
bool isConstantEvaluated() const
Definition: Sema.h:1374
clang::Sema::ActOnAddrLabel
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:16109
clang::FunctionProtoType::ExtProtoInfo::TypeQuals
Qualifiers TypeQuals
Definition: Type.h:4110
ImmediateCallVisitor::VisitCompoundStmt
bool VisitCompoundStmt(CompoundStmt *B)
Definition: SemaExpr.cpp:5957
clang::Stmt::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:337
clang::Sema::checkNonTrivialCUnion
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
Definition: SemaDecl.cpp:12980
clang::VarDecl::getPointOfInstantiation
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2696
clang::Expr::MLV_Valid
@ MLV_Valid
Definition: Expr.h:293
clang::Sema::ActOnCondition
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20390
clang::ASTContext::getPointerDiffType
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
Definition: ASTContext.cpp:6021
clang::Sema::CreateGenericSelectionExpr
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > Types, ArrayRef< Expr * > Exprs)
Definition: SemaExpr.cpp:1636
clang::sema::CapturingScopeInfo
Definition: ScopeInfo.h:669
clang::Sema::IncompatiblePointerDiscardsQualifiers
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition: Sema.h:12401
clang::InitializedEntity
Describes an entity that is being initialized.
Definition: Initialization.h:47
clang::CXXMethodDecl::getDevirtualizedMethod
CXXMethodDecl * getDevirtualizedMethod(const Expr *Base, bool IsAppleKext)
If it's possible to devirtualize a call to this method, return the called function.
Definition: DeclCXX.cpp:2248
clang::Type::isConstantArrayType
bool isConstantArrayType() const
Definition: Type.h:6966
clang::ASTContext::areCompatibleVectorTypes
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
Definition: ASTContext.cpp:9472
clang::sema::AnalysisBasedWarnings::getDefaultPolicy
Policy getDefaultPolicy()
Definition: AnalysisBasedWarnings.h:98
clang::CorrectionCandidateCallback::setTypoNNS
void setTypoNNS(NestedNameSpecifier *NNS)
Definition: TypoCorrection.h:323
clang::BlockDecl::setParams
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.cpp:4911
clang::CharLiteralParser
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Definition: LiteralSupport.h:188
clang::LookupResult::getFoundDecl
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:543
clang::LookupResult::getAsSingle
DeclClass * getAsSingle() const
Definition: Lookup.h:533
clang::Sema::ConvertParamDefaultArgument
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
Definition: SemaDeclCXX.cpp:272
clang::CXXDefaultInitExpr::Create
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field, DeclContext *UsedContext, Expr *RewrittenInitExpr)
Field is the non-static data member whose default initializer is used by this expression.
Definition: ExprCXX.cpp:1014
clang::NullabilityKind::Nullable
@ Nullable
Values of this type can be null.
clang::Qualifiers::removeObjCLifetime
void removeObjCLifetime()
Definition: Type.h:357
clang::InitializedEntity::InitializeBlock
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type)
Definition: Initialization.h:309
clang::Decl::isDefinedOutsideFunctionOrMethod
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:914
MarkVarDeclODRUsed
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:18479
clang::BuiltinType::isSVEBool
bool isSVEBool() const
Definition: Type.h:2691
clang::Sema::BuildUnaryOp
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:16057
clang::StringLiteral::getLength
unsigned getLength() const
Definition: Expr.h:1891
clang::DeclContextLookupResult
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1334
clang::SYCLUniqueStableNameExpr::Create
static SYCLUniqueStableNameExpr * Create(const ASTContext &Ctx, SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, TypeSourceInfo *TSI)
Definition: Expr.cpp:626
UsedDeclVisitor.h
clang::ArraySubscriptExpr::getBase
Expr * getBase()
Definition: Expr.h:2694
clang::sema::CapturingScopeInfo::CXXThisCaptureIndex
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition: ScopeInfo.h:689
clang::FunctionTypeLoc::getReturnLoc
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1467
clang::Sema::IncompatibleVectors
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition: Sema.h:12417
clang::Qualifiers::removeCVRQualifiers
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:301
clang::Sema::CreateBuiltinArraySubscriptExpr
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5646
clang::TypeSpecTypeLoc::setNameLoc
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:527
clang::ImplicitCastExpr
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3627
ImmediateCallVisitor::VisitLambdaExpr
bool VisitLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5949
checkConditionalBlockPointerCompatibility
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
Definition: SemaExpr.cpp:8554
clang::VAArgExpr
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4641
clang::SourceLocExpr
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4690
funcHasParameterSizeMangling
static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD)
Return true if this function has a calling convention that requires mangling in the size of the param...
Definition: SemaExpr.cpp:18088
clang::MemberExpr
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
clang::TypeLoc::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:152
clang::sema::Capture::isBlockCapture
bool isBlockCapture() const
Definition: ScopeInfo.h:627
clang::ASTContext::getBuiltinMSVaListType
QualType getBuiltinMSVaListType() const
Retrieve the type of the __builtin_ms_va_list type.
Definition: ASTContext.h:2087
clang::CXXBasePaths
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Definition: CXXInheritance.h:117
clang::CXXDependentScopeMemberExpr::Create
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1474
clang::ASTContext::getTrivialTypeSourceInfo
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
Definition: ASTContext.cpp:3075
clang::ConstraintSatisfaction
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:28
clang::Sema::LOLR_Raw
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition: Sema.h:4373
clang::QualType::getTypePtr
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6635
clang::Sema::ActOnOMPArrayShapingExpr
ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, SourceLocation RParenLoc, ArrayRef< Expr * > Dims, ArrayRef< SourceRange > Brackets)
Definition: SemaExpr.cpp:5279
clang::RecordType::getDecl
RecordDecl * getDecl() const
Definition: Type.h:4833
DiagnoseSelfAssignment
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
Definition: SemaExpr.cpp:14925
clang::sema::LambdaScopeInfo::addPotentialThisCapture
void addPotentialThisCapture(SourceLocation Loc)
Definition: ScopeInfo.h:958
CheckIncrementDecrementOperand
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn't need to call Usual...
Definition: SemaExpr.cpp:14352
clang::Sema::checkUnknownAnyCast
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
Definition: SemaExpr.cpp:20855
DiagnoseUnusedOfDecl
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:100
isLegalBoolVectorBinaryOp
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13497
clang::Sema::ACK_Comparison
@ ACK_Comparison
A comparison.
Definition: Sema.h:12337
clang::InitializedEntity::InitializeTemporary
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
Definition: Initialization.h:332
clang::Sema::DiagnoseUnusedParameters
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:14719
clang::ASTContext::getPointerType
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Definition: ASTContext.cpp:3386
clang::Builtin::Context::hasCustomTypechecking
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:196
clang::CPlusPlus11
@ CPlusPlus11
Definition: LangStandard.h:54
clang::ExtVectorType
ExtVectorType - Extended vector type.
Definition: Type.h:3486
clang::ObjCMethodDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:375
clang::Sema::NTCUK_Copy
@ NTCUK_Copy
Definition: Sema.h:3022
clang::CXXScopeSpec::MakeTrivial
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
clang::NamedDecl::isCXXClassMember
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:369
clang::sema::CapturingScopeInfo::getCXXThisCapture
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition: ScopeInfo.h:723
clang::DeclRefExpr::getQualifierLoc
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1326
clang::interp::DeclTy
unsigned llvm::PointerUnion< const Decl *, const Expr * > DeclTy
Definition: Descriptor.h:26
clang::ObjCIvarRefExpr::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:595
clang::Sema::diagnoseMissingTemplateArguments
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
Definition: SemaTemplate.cpp:4849
Parent
NodeId Parent
Definition: ASTDiff.cpp:191
clang::ReferenceType
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2887
clang::OMPIteratorExpr::IteratorDefinition
Iterator definition representation.
Definition: ExprOpenMP.h:284
clang::TypoCorrection::WillReplaceSpecifier
void WillReplaceSpecifier(bool ForceReplacement)
Definition: TypoCorrection.h:100
clang::ASTContext::ShortAccumTy
CanQualType ShortAccumTy
Definition: ASTContext.h:1091
clang::CharUnits
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
canConvertIntToOtherIntTy
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, QualType OtherIntTy)
Test if a (constant) integer Int can be casted to another integer type IntTy without losing precision...
Definition: SemaExpr.cpp:10480
clang::PointerType::getPointeeType
QualType getPointeeType() const
Definition: Type.h:2786
clang::ASTContext::Float128Ty
CanQualType Float128Ty
Definition: ASTContext.h:1090
CheckForModifiableLvalue
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:13939
clang::Sema::MarkDeclarationsReferencedInType
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
Definition: SemaExpr.cpp:20084
clang::TypeLoc::initializeFullCopy
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:202
clang::Sema::MarkVariableReferenced
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:19931
rebuildPotentialResultsAsNonOdrUsed
static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, NonOdrUseReason NOUR)
Walk the set of potential results of an expression and mark them all as non-odr-uses if they satisfy ...
Definition: SemaExpr.cpp:19344
clang::VectorType::getNumElements
unsigned getNumElements() const
Definition: Type.h:3407
clang::FunctionProtoTypeLoc
Definition: TypeLoc.h:1498
clang::LangOptions::FEM_Extended
@ FEM_Extended
Use extended type for fp arithmetic.
Definition: LangOptions.h:291
clang::Sema::getNonOdrUseReasonInCurrentContext
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
Definition: SemaExpr.cpp:2049
clang::Decl::setInvalidDecl
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
clang::Lexer::AdvanceToTokenCharacter
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition: Lexer.h:399
clang::ASTContext::getArrayDecayedType
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
Definition: ASTContext.cpp:7009
ConvertTokenKindToUnaryOpcode
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:14869
clang::ASTContext::isDependenceAllowed
bool isDependenceAllowed() const
Definition: ASTContext.h:768
clang::ObjCIvarRefExpr::getBase
const Expr * getBase() const
Definition: ExprObjC.h:580
clang::BlockDecl::setBlockMissingReturnType
void setBlockMissingReturnType(bool val=true)
Definition: Decl.h:4471
clang::sema::LambdaScopeInfo::addPotentialCapture
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas.
Definition: ScopeInfo.h:952
checkConditionalNullPointer
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:8410
clang::APValue
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
clang::isTemplateInstantiation
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:200
clang::ArraySubscriptExpr::getExprLoc
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:2712
clang::ASTContext::hasSameType
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2516
clang::Expr::refersToBitField
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:464
clang::AtomicType
Definition: Type.h:6453
clang::Sema::LookupOrdinaryName
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:4288
clang::Language::HIP
@ HIP
clang::GNUNullExpr
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4607
clang::BinaryOperator::isShiftOp
bool isShiftOp() const
Definition: Expr.h:3903
checkConditionalObjectPointersCompatibility
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:8580
clang::Sema::NTCUC_CompoundLiteral
@ NTCUC_CompoundLiteral
Definition: Sema.h:3005
clang::Sema::BuildSYCLUniqueStableNameExpr
ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, TypeSourceInfo *TSI)
Definition: SemaExpr.cpp:3583
clang::sema::CapturingScopeInfo::getCapture
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition: ScopeInfo.h:736
clang::DeclRefExpr::refersToEnclosingVariableOrCapture
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1437
clang::BlockDecl::setCaptures
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:4922
clang::Sema::IncompatibleNestedPointerQualifiers
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition: Sema.h:12413
clang::CastExpr::getCastKindName
const char * getCastKindName() const
Definition: Expr.h:3531
clang::Sema::CheckTollFreeBridgeCast
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr)
Definition: SemaExprObjC.cpp:4131
clang::sema::CapturingScopeInfo::isVLATypeCaptured
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
Definition: ScopeInfo.cpp:227
clang::StringLiteral::Create
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1185
clang::Sema::BuildParmVarDeclForTypedef
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:14706
llvm::SmallVectorImpl
Definition: Randstruct.h:18
clang::Type::isFixedPointType
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7249
clang::Sema::areVectorTypesSameSize
bool areVectorTypesSameSize(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7958
clang::FunctionType::getCallResultType
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:3971
clang::Sema::DefineImplicitLambdaToFunctionPointerConversion
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
Definition: SemaDeclCXX.cpp:15427
clang::Type::getNullability
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4182
clang::Scope::DeclScope
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:60
clang::Sema::CheckForImmediateInvocation
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17769
clang::ObjCIvarDecl::getUsageType
QualType getUsageType(QualType objectType) const
Retrieve the type of this instance variable when viewed as a member of a specific object type.
Definition: DeclObjC.cpp:1905
clang::ValueDecl::getType
QualType getType() const
Definition: Decl.h:714
clang::SC_None
@ SC_None
Definition: Specifiers.h:238
clang::Sema::CVT_Host
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition: Sema.h:13067
clang::Sema::CheckCompatibleReinterpretCast
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
Definition: SemaCast.cpp:2003
clang::CastKind
CastKind
CastKind - The kind of operation required for a conversion.
Definition: OperationKinds.h:20
clang::Scope::BreakScope
@ BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it.
Definition: Scope.h:52
clang::Type::isIntegerType
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7236
clang::Sema::LK_Numeric
@ LK_Numeric
Definition: Sema.h:3955
clang::MemberSpecializationInfo::getTemplateSpecializationKind
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:651
clang::FunctionDecl::getBuiltinID
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3413
clang::Sema::BuildBuiltinCallExpr
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:7088
enclosingClassIsRelatedToClassInWhichMembersWereFound
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:6734
clang::VarTemplateDecl
Declaration of a variable template.
Definition: DeclTemplate.h:3119
clang::Sema::forceUnknownAnyToType
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20875
clang::ASTContext::hasSameUnqualifiedType
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2543
isOdrUseContext
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use?
Definition: SemaExpr.cpp:18176
clang::Sema::DecomposeUnqualifiedId
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
Definition: SemaExpr.cpp:2146
clang::Sema::ActOnPredefinedExpr
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3605
clang::Type::STK_Bool
@ STK_Bool
Definition: Type.h:2288
clang::ArrayType::getElementType
QualType getElementType() const
Definition: Type.h:3040
Previous
StateNode * Previous
Definition: UnwrappedLineFormatter.cpp:1149
clang::Expr
This represents one expression.
Definition: Expr.h:111
clang::Expr::getValueKindForType
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:422
clang::Expr::setObjectKind
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:452
RemoveNestedImmediateInvocation
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
Definition: SemaExpr.cpp:17833
clang::HLSL
@ HLSL
Definition: LangStandard.h:63
clang::Sema::getCurrentMangleNumberContext
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:276
canConvertIntTyToFloatTy
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, QualType FloatTy)
Test if a (constant) integer Int can be casted to floating point type FloatTy without losing precisio...
Definition: SemaExpr.cpp:10518
clang::ASTContext::getTypeInfo
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
Definition: ASTContext.cpp:2013
clang::CXXScopeSpec::isEmpty
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:191
clang::sema::Capture::getVariable
ValueDecl * getVariable() const
Definition: ScopeInfo.h:646
captureInCapturedRegion
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the captured region.
Definition: SemaExpr.cpp:18789
clang::Type::isSpecificBuiltinType
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7173
clang::OpaquePtr< QualType >::getFromOpaquePtr
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
clang::NK_Dependent_Narrowing
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:247
clang::Sema::checkSYCLDeviceFunction
bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition: SemaSYCL.cpp:36
clang::Expr::isModifiableLvalueResult
isModifiableLvalueResult
Definition: Expr.h:292
clang::ParmVarDecl::Create
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2834
clang::Expr::ConstantExprKind::ImmediateInvocation
@ ImmediateInvocation
An immediate invocation.
clang::ASTContext::setBOOLDecl
void setBOOLDecl(TypedefDecl *TD)
Save declaration of 'BOOL' typedef.
Definition: ASTContext.h:2054
handleComplexFloatConversion
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
Definition: SemaExpr.cpp:1117
clang::CXXDefaultInitExpr
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1354
clang::ASTContext::isObjCSelType
bool isObjCSelType(QualType T) const
Definition: ASTContext.h:2842
clang::QualType::isDestructedType
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1288
clang::VarDecl::hasLocalStorage
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1143
clang::CXXScopeSpec::getRange
SourceRange getRange() const
Definition: DeclSpec.h:70
HandleImmediateInvocations
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
Definition: SemaExpr.cpp:17921
handleComplexConversion
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1140
clang::CXXCtorInitializer
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2219
clang::Type::isUnsignedIntegerType
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2092
clang::BlockDecl::Capture
A class which contains all the information about a particular captured value.
Definition: Decl.h:4338
clang::Sema::BuildResolvedCallExpr
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
Definition: SemaExpr.cpp:7154
clang::Sema::getCurrentThisType
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
Definition: SemaExprCXX.cpp:1191
clang::CXXDefaultArgExpr::Create
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition: ExprCXX.cpp:960
clang::TSK_ImplicitInstantiation
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:182
clang::QualType::addConst
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:912
clang::StringLiteralParser
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
Definition: LiteralSupport.h:218
clang::ObjCMethodDecl::isClassMethod
bool isClassMethod() const
Definition: DeclObjC.h:436
clang::Expr::isSameComparisonOperand
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr's will refer to the same value as a comparison operand.
Definition: Expr.cpp:4108
clang::Sema::PP
Preprocessor & PP
Definition: Sema.h:408
clang::EnumType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:4849
DiagnoseBitwiseOpInBitwiseOp
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *SubExpr)
Look for bitwise op in the left or right hand of a bitwise op with lower precedence and emit a diagno...
Definition: SemaExpr.cpp:15482
clang::UnqualifiedIdKind::IK_ImplicitSelfParam
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
isVector
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
Definition: SemaExpr.cpp:9735
clang::DeclContext::isFunctionOrMethod
bool isFunctionOrMethod() const
Definition: DeclBase.h:1981
clang::Sema::LOLR_Cooked
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition: Sema.h:4370
clang::CXXScopeSpec::getBeginLoc
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:74
clang::FunctionProtoType::getExtParameterInfo
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:4436
clang::Sema::ActOnOMPArraySectionExpr
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc)
Definition: SemaExpr.cpp:5093
clang::Type::STK_ObjCObjectPointer
@ STK_ObjCObjectPointer
Definition: Type.h:2286
clang::FunctionProtoType::getExtProtoInfo
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4245
clang::NK_Not_Narrowing
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:233
clang::ASTContext::getObjCObjectPointerType
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
Definition: ASTContext.cpp:5642
clang::OMPIteratorExpr::IteratorRange::End
Expr * End
Definition: ExprOpenMP.h:280
clang::DeclarationNameInfo::getLoc
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
Definition: DeclarationName.h:796
clang::Sema::MarkFunctionReferenced
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:18220
clang::Sema::TryCaptureKind
TryCaptureKind
Definition: Sema.h:5437
clang::DeclarationNameInfo
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
Definition: DeclarationName.h:767
clang::Type::isIncompleteType
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2258
clang::CastExpr
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3483
clang::ASTContext::getConstantArrayType
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
Definition: ASTContext.cpp:3618
clang::Sema::NSAPIObj
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:1173
clang::Sema::NeedToCaptureVariable
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:19292
clang::NullabilityKind::NonNull
@ NonNull
Values of this type can never be null.
clang::InitializationKind::CreateCopy
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
Definition: Initialization.h:673
NestedConstMember
@ NestedConstMember
Definition: SemaExpr.cpp:13742
clang::FunctionDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2584
clang::Sema::ActOnCompoundLiteral
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:7447
clang::sema::CapturedRegionScopeInfo::OpenMPLevel
unsigned short OpenMPLevel
Definition: ScopeInfo.h:798
clang::ASTContext::CreateTypeSourceInfo
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
Definition: ASTContext.cpp:3061
clang::Decl::getLocation
SourceLocation getLocation() const
Definition: DeclBase.h:432
clang::format::Base
Base
Definition: IntegerLiteralSeparatorFixer.cpp:20
clang::sema::CapturingScopeInfo::ReturnType
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:700
clang::Qualifiers::setAddressSpace
void setAddressSpace(LangAS space)
Definition: Type.h:397
clang::CXXRecordDecl::getTemplateInstantiationPattern
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1886
CheckVecStepTraitOperandType
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4173
clang::Type::isUnscopedEnumerationType
bool isUnscopedEnumerationType() const
Definition: Type.cpp:1978
clang::Sema::CheckPointerConversion
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
Definition: SemaOverload.cpp:3100
clang::Sema::DiagnoseUnusedExprResult
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition: SemaStmt.cpp:219
clang::Decl::setReferenced
void setReferenced(bool R=true)
Definition: DeclBase.h:606
clang::ASTContext::BoolTy
CanQualType BoolTy
Definition: ASTContext.h:1079
clang::Sema::DiagnoseConditionalForNull
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
Definition: SemaExpr.cpp:8351
clang::DeclRefExpr
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1235
clang::ConstantMatrixType::getNumRows
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:3609
clang::NamespaceDecl
Represent a C++ namespace.
Definition: Decl.h:542
diagnoseLogicalNotOnLHSofCheck
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
Definition: SemaExpr.cpp:12222
clang::ASTContext::mergeTypes
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
Definition: ASTContext.cpp:10490
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1917
clang::PredefinedExpr::Func
@ Func
Definition: Expr.h:1983
clang::Sema::BuildCompoundLiteralExpr
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
Definition: SemaExpr.cpp:7461
clang::Sema::prepareVectorSplat
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:8099
clang::RecordDecl
Represents a struct/union/class.
Definition: Decl.h:3996
clang::StringLiteral::Ordinary
@ Ordinary
Definition: Expr.h:1801
clang::DeclContext::Equals
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2053
clang::BlockDecl::getCaretLocation
SourceLocation getCaretLocation() const
Definition: Decl.h:4405
clang::Sema::UndefinedButUsed
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:1494
clang::PredefinedExpr::FuncSig
@ FuncSig
Definition: Expr.h:1987
clang::CallExpr
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2813
clang::Sema::HandleExprEvaluationContextForTypeof
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:18045
clang::CXXDefaultArgExpr::getExpr
Expr * getExpr()
Definition: ExprCXX.cpp:971
clang::CXXOperatorCallExpr
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
clang::DeclarationNameInfo::getBeginLoc
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
Definition: DeclarationName.h:869
clang::Sema::checkPseudoObjectIncDec
ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
Definition: SemaPseudoObject.cpp:1552
clang::ObjCInterfaceType
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6227
clang::OverloadExpr::FindResult::IsAddressOfOperand
bool IsAddressOfOperand
Definition: ExprCXX.h:3005
clang::ObjCPropertyDecl::findPropertyDecl
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:178
clang::ASTContext::typesAreBlockPointerCompatible
bool typesAreBlockPointerCompatible(QualType, QualType)
Definition: ASTContext.cpp:10225
clang::ASTContext::getStringLiteralArrayType
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
Definition: ASTContext.cpp:12172
clang::Expr::NPCK_NotNull
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:771
clang::LookupResult::getLookupNameInfo
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:233
clang::DeclarationNameTable::getCXXLiteralOperatorName
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
Definition: DeclarationName.cpp:368
clang::Sema::CheckBooleanCondition
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
Definition: SemaExpr.cpp:20359
breakDownVectorType
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:7904
clang::FunctionDecl::isDefined
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3085
clang::ObjCIvarRefExpr
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:548
diagnoseArithmeticOnFunctionPointer
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:11196
clang::NOUR_Constant
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition: Specifiers.h:168
clang::TemplateArgumentLocInfo
Location information for a TemplateArgument.
Definition: TemplateBase.h:432
clang::Sema::IdentifyCUDATarget
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:116
clang::Type::isIncompleteOrObjectType
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2057
clang::ActionResult::isUsable
bool isUsable() const
Definition: Ownership.h:166
clang::Sema::LK_Block
@ LK_Block
Definition: Sema.h:3958
clang::IdentifierInfo::isEditorPlaceholder
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
Definition: IdentifierTable.h:454
clang::MatrixType
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:3555
clang::Sema::ActOnCallExpr
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6846
clang::ICK_Integral_Conversion
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
clang::Sema::DiagnoseAssignmentAsCondition
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
Definition: SemaExpr.cpp:20274
IsInvalidCmseNSCallConversion
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:9464
isObjCObjectLiteral
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:12071
clang::ASTContext::getLangOpts
const LangOptions & getLangOpts() const
Definition: ASTContext.h:762
clang::ASTContext::ShortFractTy
CanQualType ShortFractTy
Definition: ASTContext.h:1094
clang::Sema::BuildVectorLiteral
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:8240
clang::TargetInfo::getIntWidth
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:477
clang::Sema::LK_None
@ LK_None
Definition: Sema.h:3959
clang::Sema::setFunctionHasBranchProtectedScope
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2288
clang::Sema::ActOnStmtExprError
void ActOnStmtExprError()
Definition: SemaExpr.cpp:16126
clang::CharUnits::getQuantity
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
clang::BinaryOperator::isMultiplicativeOp
bool isMultiplicativeOp() const
Definition: Expr.h:3899
clang::LookupResult::getRepresentativeDecl
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:550
clang::InitializationKind::CreateCStyleCast
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
Definition: Initialization.h:654
clang::prec::Shift
@ Shift
Definition: OperatorPrecedence.h:39
clang::UnnamedGlobalConstantDecl
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4257
clang::LookupResult::isOverloadedResult
bool isOverloadedResult() const
Determines if the results are overloaded.
Definition: Lookup.h:313
clang::Sema::DefineDefaultedComparison
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
Definition: SemaDeclCXX.cpp:8858
clang::DeclaratorDecl::getTypeSourceInfo
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:796
clang::FixItHint::CreateReplacement
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
clang::Sema::ActOnBlockStmtExpr
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
Definition: SemaExpr.cpp:16589
clang::ExplicitCastExpr
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3705
clang::VarDecl::hasDefinition
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2304
clang::Sema::PrepareCastToObjCObjectPointer
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
Definition: SemaExpr.cpp:7682
clang::Expr::MLV_NoSetterProperty
@ MLV_NoSetterProperty
Definition: Expr.h:304
clang::DiagnosticsEngine::getSuppressSystemWarnings
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:685
clang::Type::isIntegralOrEnumerationType
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:7307
clang::CXXMethodDecl::isVirtual
bool isVirtual() const
Definition: DeclCXX.h:2039
clang::OMPIteratorExpr::IteratorDefinition::SecondColonLoc
SourceLocation SecondColonLoc
Definition: ExprOpenMP.h:288
clang::TargetInfo::useFP16ConversionIntrinsics
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:926
clang::Sema::PoppedFunctionScopePtr
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:1980
clang::Sema::CheckCUDACall
bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition: SemaCUDA.cpp:784
clang::FunctionCallFilterCCC::ValidateCandidate
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
Definition: SemaLookup.cpp:5612
clang::ExplicitCastExpr::getTypeAsWritten
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3732
ContextKind
tok::TokenKind ContextKind
Definition: TokenAnnotator.cpp:1637
clang::TargetInfo::hasBuiltinMSVaList
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:967
EvaluateAndDiagnoseImmediateInvocation
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
Definition: SemaExpr.cpp:17799
clang::ASTContext::getMemberPointerType
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
Definition: ASTContext.cpp:3588
TypeLoc.h
clang::Sema::ExpressionEvaluationContextRecord::ReferenceToConsteval
llvm::SmallPtrSet< DeclRefExpr *, 4 > ReferenceToConsteval
Set of DeclRefExprs referencing a consteval function when used in a context not already known to be i...
Definition: Sema.h:1326
isImplicitlyDefinableConstexprFunction
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:18208
clang::declaresSameEntity
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1240
clang::TypeSourceInfo::getTypeLoc
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:244
clang::Sema::IncompatibleFunctionPointerStrict
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition: Sema.h:12386
clang::ValueDecl::setType
void setType(QualType newType)
Definition: Decl.h:715
clang::Sema::LookupMethodInObjectType
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
Definition: SemaExprObjC.cpp:1934
ParsedTemplate.h
clang::sema::FunctionScopeInfo::addBlock
void addBlock(const BlockDecl *BD)
Definition: ScopeInfo.h:478
clang::Sema::ExpressionEvaluationContext::ImmediateFunctionContext
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
checkObjCPointerTypesForAssignment
static Sema::AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
Definition: SemaExpr.cpp:9686
clang::getAsTypeTemplateDecl
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
Definition: DeclTemplate.h:3432
Initialization.h
clang::UnqualifiedId::setImplicitSelfParam
void setImplicitSelfParam(const IdentifierInfo *Id)
Specify that this unqualified-id is an implicit 'self' parameter.
Definition: DeclSpec.h:1175
clang::CXXMethodDecl::getParent
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2110
clang::CXXMethodDecl
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1995
clang::Sema::ActOnGenericSelectionExpr
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr * > ArgExprs)
Definition: SemaExpr.cpp:1611
clang::CXXScopeSpec::isInvalid
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:196
CheckForNullPointerDereference
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:548
checkArithmeticOnObjCPointer
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4765
clang::Sema::getDefaultedComparisonKind
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition: Sema.h:3433
clang::UnaryExprOrTypeTrait
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
clang::Sema::checkRetainCycles
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
Definition: SemaChecking.cpp:16849
clang::Type::isUndeducedType
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7326
clang::ImplicitConversionSequence
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:517
clang::LookupResult::isAmbiguous
bool isAmbiguous() const
Definition: Lookup.h:301
clang::ConstexprSpecKind::Unspecified
@ Unspecified
clang::Sema::CorrectDelayedTyposInExpr
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
Definition: SemaExprCXX.cpp:8747
clang::Decl::getDeclContext
DeclContext * getDeclContext()
Definition: DeclBase.h:441
clang::OMPIteratorExpr::IteratorDefinition::Range
IteratorRange Range
Definition: ExprOpenMP.h:286
clang::CallExpr::shrinkNumArgs
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition: Expr.h:3036
clang::Sema::ExpressionEvaluationContext::PotentiallyEvaluated
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
clang::Sema::CheckSwitchCondition
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1026
clang::sema::CapturingScopeInfo::isCXXThisCaptured
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:720
clang::Sema::areMatrixTypesOfTheSameDimension
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
Definition: SemaExpr.cpp:7947
isVariableAlreadyCapturedInScopeInfo
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:18590
clang::NamedDecl::getName
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:274
DoMarkPotentialCapture
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
Definition: SemaExpr.cpp:19722
buildLambdaCaptureFixit
static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, ValueDecl *Var)
Create up to 4 fix-its for explicit reference and value capture of Var or default capture.
Definition: SemaExpr.cpp:18960